I have tried using two different libraries to handle this issue and both time I get the same behavior.
Libraries tried: OvermindJS, Hookstate
When I click the button I can see the state change is beeing logged in the console but the component will only re-render on the second click
If I change page:
click Home
click Page1
click No Funds
Then it will show 1$
If I click straightway the No Funds button without changing page (first action on page) then the button will not re-render until it is clicked twice.
App.tsx
import * as React from "react"
import {
ChakraProvider,
Box,
Text,
Grid,
theme,
} from "#chakra-ui/react"
import { Switch, Route } from "wouter"
import { Appbar } from "./common/AppBar"
export const App = () => (
<ChakraProvider theme={theme}>
<Appbar />
<Box textAlign="center" fontSize="xl">
<Grid minH="100vh" p={3}>
<Switch>
<Route path="/">
<Text mt={100}>Home</Text>
</Route>
<Route path="/home">
<Text mt={100}>Home</Text>
</Route>
<Route path="/page1">
<Text mt={100}>Page 1</Text>
</Route>
</Switch>
</Grid>
</Box>
</ChakraProvider>
)
AppBar.tsx
import React, { ReactNode } from "react";
import {
Box,
Flex,
HStack,
Link,
IconButton,
Button,
Icon,
useDisclosure,
useColorModeValue,
Stack,
} from '#chakra-ui/react';
import { HamburgerIcon, CloseIcon } from '#chakra-ui/icons';
import { MdAccountBalanceWallet } from 'react-icons/md'
import { useLocation } from 'wouter';
import { actionIncrementFunds, globalState } from "../hookState/state";
import { useState } from "#hookstate/core";
const Links = ['Home', 'Page1'];
const NavLink: React.FC<any> = ({ children, handleClick }: { children: ReactNode, handleClick: any }) => (
<Link
px={2}
py={1}
rounded={'md'}
_hover={{
textDecoration: 'none',
bg: useColorModeValue('red.200', 'red.300'),
}}
onClick={() => handleClick(children)}>
{children}
</Link>
);
export const Appbar: React.FC = () => {
const state = useState(globalState);
const { isOpen, onOpen, onClose } = useDisclosure();
const [location, setLocation] = useLocation();
const handleClick = (path: string) => {
setLocation(`/${path.toLowerCase()}`)
}
const hasFunds = () => {
return state.currentFunds.get() > 0
}
const handleConnectWallet = () => {
actionIncrementFunds()
}
return (
<>
<Box zIndex={900} position={"fixed"} top={0} left={0} width="100%" bg={useColorModeValue('gray.100', 'gray.900')} px={4}>
<Flex h={16} alignItems={'center'} justifyContent={'space-between'}>
<IconButton
size={'md'}
icon={isOpen ? <CloseIcon /> : <HamburgerIcon />}
aria-label={'Open Menu'}
display={{ md: 'none' }}
onClick={isOpen ? onClose : onOpen}
/>
<HStack height={"100%"} spacing={8} alignItems={'center'}>
<HStack
as={'nav'}
spacing={4}
display={{ base: 'none', md: 'flex' }}>
{Links.map((link) => (
<NavLink handleClick={handleClick} key={link}>{link}</NavLink>
))}
</HStack>
</HStack>
<Flex alignItems={'center'}>
{hasFunds()
? <Button
variant={'solid'}
colorScheme={'red'}
size={'md'}
onClick={handleConnectWallet}
mr={4}>
{state.currentFunds.get()} $
</Button>
: <Button
variant={'solid'}
colorScheme={'red'}
size={'md'}
mr={4}
onClick={handleConnectWallet}
leftIcon={<Icon as={MdAccountBalanceWallet} />}>
No Funds
</Button>
}
</Flex>
</Flex>
{
isOpen ? (
<Box pb={4} display={{ md: 'none' }}>
<Stack as={'nav'} spacing={4}>
{Links.map((link) => (
<NavLink handleClick={handleClick} key={link}>{link}</NavLink>
))}
</Stack>
</Box>
) : null
}
</Box >
</>
);
}
Behavior example:
Repo with example for Hookstate:
https://github.com/crimson-med/state-issue
Repo with example for OvermindJS:
https://github.com/crimson-med/state-issue/tree/overmind
How can I get the button on change on the first click?
Material-ui component is not rendering in react class based component ?
I am trying to convert function based material-ui component in class based component but the class based component is not rendering... in main div in inspect main div not showing that component?
any idea how to use material-ui with class based component?
enter code here
import * as React from 'react';
import Box from '#mui/material/Box';
import Tabs from '#mui/material/Tabs';
import Tab from '#mui/material/Tab';
function LinkTab(props) {
return (
<Tab
component="a"
onClick={(event) => {
event.preventDefault();
}}
{...props}
/>
);
}
class Header extends Component {
constructor(props) {
super(props);
this.state = {
value: 0,
};
}
handleChange = (event, newValue) => {
this.setState(
(prevState) => (
{
value: newValue,
},
() => {
console.log("value", this.state.newValue);
}
)
);
};
render() {
return (
<Box sx={{ width: '100%' }}>
<Tabs value={this.state.value} onChange={this.handleChange()} aria-label="nav tabs example">
<LinkTab label="Page One" href="/drafts" />
<LinkTab label="Page Two" href="/trash" />
<LinkTab label="Page Three" href="/spam" />
</Tabs>
</Box>
);
}
}
export default Header;
import * as React from 'react';
import Box from '#mui/material/Box';
import Tabs from '#mui/material/Tabs';
import Tab from '#mui/material/Tab';
function LinkTab(props) {
return (
<Tab
component="a"
onClick={(event) => {
event.preventDefault();
}}
{...props}
/>
);
}
export default function header() {
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<Box sx={{ width: '100%' }}>
<Tabs value={value} onChange={handleChange} aria-label="nav tabs example">
<LinkTab label="Page One" href="/drafts" />
<LinkTab label="Page Two" href="/trash" />
<LinkTab label="Page Three" href="/spam" />
</Tabs>
</Box>
);
}
Replace
<Tabs value={this.state.value} onChange={this.handleChange()}
by
<Tabs value={this.state.value} onChange={this.handleChange}
Replace
handleChange = (event, newValue) => {
this.setState(
(prevState) => (
{
value: newValue,
},
() => {
console.log("value", this.state.newValue);
}
)
);
};
by
handleChange = (event, newValue) => {
this.setState(
{value: newValue},
() => {
console.log("value", this.state.newValue);
}
);
};
I'm new to React and made the code below
Where I'm trying to insert a TabPanel but it's getting an error
Uncaught TypeError: No TabContext provided at TabPanel (TabPanel.js:26)
at renderWithHooks (react-dom.development.js:14803)
How do I adjust this error?
import React, {useState, useEffect} from "react";
import TextField from '#material-ui/core/TextField';
import Button from '#material-ui/core/Button';
import MenuItem from '#material-ui/core/MenuItem';
import Fetch from "../../../services/Fetch";
import InputDatePicker from "../../../components/InputDatepicker";
import CurrencyTextField from '#unicef/material-ui-currency-textfield';
import bridge from "./bridge";
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import TabPanel from '#material-ui/lab/TabPanel';
export default (props)=>{
const [state, setState] = useState(bridge.getForm(props.idUsidUser));
const [value, setValue] = useState(0);
useEffect(()=>{
setTimeout(()=>{
var elements = document.querySelectorAll("div[min='0']");
elements.forEach((element) => {
if(element.children.length > 0){
element.children[0].min = 0;
}
});
}, 300);
}, []);
bridge.setForm = setState;
const closeModal = (event) =>{
document.querySelector("#form").removeAttribute("style");
document.querySelector("html").removeAttribute("style");
document.querySelector(".modal-overlay").removeAttribute("style");
}
const onInputChange = (event) => {
setState({
...state,
[event.target.name]: event.target.value
});
}
const handleChange = (event, newValue) => {
setValue(newValue);
};
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
return (
<form onSubmit={onSubmit}>
<h3 className="featured">Create</h3>
<Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
<Tab label="Tab 1" {...a11yProps(0)} />
<Tab label="Tab 2" {...a11yProps(1)} />
<Tab label="Tab 3" {...a11yProps(2)} />
<Tab label="Tab 4" {...a11yProps(3)} />
<Tab label="Tab 5" {...a11yProps(4)} />
</Tabs>
<TabPanel value={value} index={0}>
Item One
</TabPanel>
</form>
);
}
I don't know what I did wrong for React to acknowledge the error.
What to do in this case? Well, I followed the basic principles that I studied in the framework documentation
Comments were a little confusing for me, so here's a clear answer for others who run into this:
The error comes when using the Material UI Basic Tabs demo. They use a 'TabPanel' component in this, but as defined by their function as shown in the full code of their example (see snippet below)
The other type of TabPanel is part of the MUI labs and is imported from MUI directly:
import TabPanel from '#mui/lab/TabPanel';
But that won't work with the code in their demo example.
Demo link: https://mui.com/material-ui/react-tabs/
So if you are using the demo on the page quoted, you also need to use the same function they use:
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
I'm new to react.js and material UI, i'm try to make a Navigation top navbar for my project,
i use the 'MenuList' composition to my top navbar, the first one Button is success,but when i add another one and click it, it will overlapping with first menu list. Can someone give some hints? Thank you all.
here is the problem image
and here is my navbar source code
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Paper from '#material-ui/core/Paper';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import ClickAwayListener from '#material-ui/core/ClickAwayListener';
import Button from '#material-ui/core/Button';
import Grow from '#material-ui/core/Grow';
import Popper from '#material-ui/core/Popper';
import MenuItem from '#material-ui/core/MenuItem';
import MenuList from '#material-ui/core/MenuList';
import { Link, Route, withRouter } from 'react-router-dom';
const useStyles = makeStyles({
root: {
flexGrow: 1,
},
});
export default function CenteredTabs() {
const classes = useStyles();
const [value, setValue] = React.useState(0);
const [open, setOpen] = React.useState(false);
const anchorRef = React.useRef(null);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const handleToggle = () => {
setOpen(prevOpen => !prevOpen);
};
const handleClose = event => {
if (anchorRef.current && anchorRef.current.contains(event.target)) {
return;
}
setOpen(false);
};
function handleListKeyDown(event) {
if (event.key === 'Tab') {
event.preventDefault();
setOpen(false);
}
}
// return focus to the button when we transitioned from !open -> open
const prevOpen = React.useRef(open);
React.useEffect(() => {
if (prevOpen.current === true && open === false) {
anchorRef.current.focus();
}
prevOpen.current = open;
}, [open]);
return (
<Paper className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="secondary"
textColor="primary"
>
<Tab label="WeniPay" to="/" component={Link} style={{ float: "left" }} />
<Tab label="Home" to="/" component={Link} />
<Tab label="Login" to="/works" component={Link} />
<Tab label="Pay" to="/payPage" component={Link} />
</Tabs>
<Button
ref={anchorRef}
aria-controls={open ? 'menu-list-grow' : undefined}
aria-haspopup="true"
onClick={handleToggle}
>
Toggle Menu Grow
</Button>
<Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}
>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
<Button
ref={anchorRef}
aria-controls={open ? 'menu-list-grow' : undefined}
aria-haspopup="true"
onClick={handleToggle}
>
s
</Button>
<Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}
>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
<MenuItem onClick={handleClose}>1</MenuItem>
<MenuItem onClick={handleClose}>2</MenuItem>
<MenuItem onClick={handleClose}>3</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</Paper>
);
}
and here is main page
import React from 'react';
import styles from './App.module.scss';
import { Link, Route, withRouter } from 'react-router-dom';
import HomePage from './HomePage';
import WorkPage from './WorkPage';
import WorkPageDetail from './WorkPageDetail';
import Header from './header';
import PayPage from './PayPage';
class App extends React.Component {
render() {
const { location } = this.props;
return (
<div className={styles.App}>
{/* header */}
<header className={styles.header}>
<div className={styles.box}>
<Header />
</div>
</header>
{/* content */}
<section className={styles.content}>
<Route path="/" exact component={HomePage} />
<Route path="/works" exact component={WorkPage} />
<Route path="/works/:id" exact component={WorkPageDetail} />
<Route path="/payPage" exact component={PayPage} />
</section>
{/* footer */}
<footer className={styles.footer}>
<p>© <b>MyPay</b></p>
</footer>
</div>
);
}
}
export default withRouter(App);
You can make archorEl as array so you can set like
// set anchor as empty list so we can track it later
const [anchorEl, setAnchorEl] = React.useState<[] | HTMLElement[]>([]));
const openMenu = (event, index) => {
const tempAnchor = anchorEl;
tempAnchor[index] = event.currentTarget; // only set change version
setAnchorEl(tempAnchor);
};
const closeMenu = () => {
setAnchorEl([]); // now we set it to empty list
}
and our tsx would be like
<Menu
id={row.id}
anchorEl={anchorEl[index]}
keepMounted
open={Boolean(anchorEl[index])}
onClose={() => closeMenu()}
>
<MenuItem> Foo</MenuItem>
<MenuItem> Bar</MenuItem>
</Menu>
The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?
In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:
const TabLink = ({ onClick, href, isActive, label }) =>
<Tab
label={label}
onActive={onClick}
/>
export default class NavBar extends React.Component {
render () {
return (
<Tabs>
<Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
<Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
<Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
</Tabs>
)
}
}
But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?
Thanks in advance
Another solution (https://codesandbox.io/s/l4yo482pll) with no handlers nor HOCs, just pure react-router and material-ui components:
import React, { Fragment } from "react";
import ReactDOM from "react-dom";
import Tabs from "#material-ui/core/Tabs";
import Tab from "#material-ui/core/Tab";
import { Switch, Route, Link, BrowserRouter, Redirect } from "react-router-dom";
function App() {
const allTabs = ['/', '/tab2', '/tab3'];
return (
<BrowserRouter>
<div className="App">
<Route
path="/"
render={({ location }) => (
<Fragment>
<Tabs value={location.pathname}>
<Tab label="Item One" value="/" component={Link} to={allTabs[0]} />
<Tab label="Item Two" value="/tab2" component={Link} to={allTabs[1]} />
<Tab
value="/tab3"
label="Item Three"
component={Link}
to={allTabs[2]}
/>
</Tabs>
<Switch>
<Route path={allTabs[1]} render={() => <div>Tab 2</div>} />
<Route path={allTabs[2]} render={() => <div>Tab 3</div>} />
<Route path={allTabs[0]} render={() => <div>Tab 1</div>} />
</Switch>
</Fragment>
)}
/>
</div>
</BrowserRouter>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
My instructor helped me with using React Router 4.0's withRouter to wrap the Tabs component to enable history methods like so:
import React, {Component} from "react";
import {Tabs, Tab} from 'material-ui';
import { withRouter } from "react-router-dom";
import Home from "./Home";
import Portfolio from "./Portfolio";
class NavTabs extends Component {
handleCallToRouter = (value) => {
this.props.history.push(value);
}
render () {
return (
<Tabs
value={this.props.history.location.pathname}
onChange={this.handleCallToRouter}
>
<Tab
label="Home"
value="/"
>
<div>
<Home />
</div>
</Tab>
<Tab
label="Portfolio"
value="/portfolio"
>
<div>
<Portfolio />
</div>
</Tab>
</Tabs>
)
}
}
export default withRouter(NavTabs)
Simply add BrowserRouter to index.js and you're good to go.
The error you are seeing from material-ui is because it expects to have a <Tab> component rendered as direct child of <Tabs> component.
Now, here is a way that I've found to integrate the link into the <Tabs> component without loosing the styles:
import React, {Component} from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import {Link} from 'react-router-dom';
export default class MyComponent extends Component {
render() {
const {location} = this.props;
const {pathname} = location;
return (
<Tabs value={pathname}>
<Tab label="First tab" containerElement={<Link to="/my-firs-tab-view" />} value="/my-firs-tab-view">
{/* insert your component to be rendered inside the tab here */}
</Tab>
<Tab label="Second tab" containerElement={<Link to="/my-second-tab-view" />} value="/my-second-tab-view">
{/* insert your component to be rendered inside the tab here */}
</Tab>
</Tabs>
);
}
}
To manage the 'active' property for the tabs, you can use the value property in the <Tabs> component and you also need to have a value property for each tab, so when both of the properties match, it will apply the active style to that tab.
Solution with Tab highlight, Typescript based and works well with react-route v5:
Explanation: <Tab/> here work as a link to React router. Values in <Tab/> to={'/all-event'} and value={'/all-event'} should be same in order to highlgiht
import { Container, makeStyles, Tab, Tabs } from '#material-ui/core';
import React from 'react';
import {
Link,
Route,
Switch,
useLocation,
Redirect,
} from 'react-router-dom';
import AllEvents from './components/AllEvents';
import UserEventsDataTable from './components/UserEventsDataTable';
const useStyles = makeStyles(() => ({
container: {
display: 'flex',
justifyContent: 'center',
},
}));
function App() {
const classes = useStyles();
const location = useLocation();
return (
<>
<Container className={classes.container}>
<Tabs value={location.pathname}>
<Tab
label='All Event'
component={Link}
to={`/all-event`}
value={`/all-event`}
/>
<Tab
label='User Event'
component={Link}
to={`/user-event`}
value={`/user-event`}
/>
</Tabs>
</Container>
<Switch>
<Route path={`/all-event`}>
<AllEvents />
</Route>
<Route path={`/user-event`}>
<UserEventsDataTable />
</Route>
<Route path={`/`}>
<Redirect from='/' to='/all-event' />
</Route>
</Switch>
</>
);
}
export default App;
Here's another solution, using the beta of Material 1.0 and adding browser Back/Forward to the mix:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Tabs, { Tab } from 'material-ui/Tabs';
import { withRouter } from "react-router-dom";
import Home from "./Home";
import Portfolio from "./Portfolio";
function TabContainer(props) {
return <div style={{ padding: 20 }}>{props.children}</div>;
}
const styles = theme => ({
root: {
flexGrow: 1,
width: '100%',
marginTop: theme.spacing.unit * 3,
backgroundColor: theme.palette.background.paper,
},
});
class NavTabs extends React.Component {
state = {
value: "/",
};
componentDidMount() {
window.onpopstate = ()=> {
this.setState({
value: this.props.history.location.pathname
});
}
}
handleChange = (event, value) => {
this.setState({ value });
this.props.history.push(value);
};
render() {
const { classes } = this.props;
const { value } = this.state;
return (
<div className={classes.root}>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={this.handleChange}
scrollable
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
>
<Tab label="Home" value = "/" />
<Tab label="Portfolio" value = "/portfolio"/>
</Tabs>
</AppBar>
{value === "/" && <TabContainer>{<Home />}</TabContainer>}
{value === "/portfolio" && <TabContainer>{<Portfolio />}</TabContainer>}
</div>
);
}
}
NavTabs.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withRouter(withStyles(styles)(NavTabs));
You can use browserHistory instead of React-Router Link component
import { browserHistory } from 'react-router'
// Go to /some/path.
onClick(label) {
browserHistory.push('/${label}');
}
// Example for Go back
//browserHistory.goBack()
<Tabs>
<Tab
label={label}
onActive={() => onClick(label)}
/>
</Tabs>
As you see you can simply push() your target to the browserHistory
As #gkatchmar says you can use withRouter high-order component but you can also use context API. Since #gkatchmar showed withRouter already I will only show context API. Bear in mind that this is an experimental API.
https://stackoverflow.com/a/42716055/3850405
import React, {Component} from "react";
import {Tabs, Tab} from 'material-ui';
import * as PropTypes from "prop-types";
export class NavTabs extends Component {
constructor(props) {
super(props);
}
static contextTypes = {
router: PropTypes.object
}
handleChange = (event: any , value: any) => {
this.context.router.history.push(value);
};
render () {
return (
<Tabs
value={this.context.router.history.location.pathname}
onChange={this.handleChange}
>
<Tab
label="Home"
value="/"
>
<div>
<Home />
</div>
</Tab>
<Tab
label="Portfolio"
value="/portfolio"
>
<div>
<Portfolio />
</div>
</Tab>
</Tabs>
)
}
}
Here's a simple solution using the useLocation hook. No state needed. React router v5 though.
import { Tab, Tabs } from '#material-ui/core';
import { matchPath, NavLink, useLocation } from 'react-router-dom';
const navItems = [
{
id: 'one',
path: '/one',
text: 'One',
},
{
id: 'two',
path: '/two',
text: 'Two',
},
{
id: 'three',
path: '/three',
text: 'Three',
},
];
export default function Navigation() {
const { pathname } = useLocation();
const activeItem = navItems.find((item) => !!matchPath(pathname, { path: item.path }));
return (
<Tabs value={activeItem?.id}>
{navItems.map((item) => (
<Tab key={item.id} value={item.id} label={item.text} component={NavLink} to={item.path} />
))}
</Tabs>
);
}
<BrowserRouter>
<div className={classes.root}>
<AppBar position="static" color="default">
<Tabs
value={this.state.value}
onChange={this.handleChange}
indicatorColor="primary"
textColor="primary"
fullWidth
>
<Tab label="Item One" component={Link} to="/one" />
<Tab label="Item Two" component={Link} to="/two" />
</Tabs>
</AppBar>
<Switch>
<Route path="/one" component={PageShell(ItemOne)} />
<Route path="/two" component={PageShell(ItemTwo)} />
</Switch>
</div>
I've created this hook to help control the tabs and generate the default value that catches from the location URL.
const useTabValue = (array, mainPath = "/") => {
const history = useHistory();
const { pathname } = useLocation();
const [value, setValue] = useState(0);
const pathArray = pathname.split("/");
function handleChange(_, nextEvent) {
setValue(nextEvent);
history.push(`${mainPath}/${array[nextEvent]}`);
}
const findDefaultValue = useCallback(() => {
return array.forEach((el) => {
if (pathArray.indexOf(el) > 0) {
setValue(array.indexOf(el));
return;
}
});
}, [pathArray, array]);
useEffect(() => {
findDefaultValue();
}, [findDefaultValue]);
return {
handleChange,
value,
};
};
then I have used it like this :
const NavigationBar = () => {
const classes = useStyles();
const allTabs = useMemo(() => ["home", "search"]);
const { handleChange, value } = useTabValue(allTabs, "/dashboard");
return (
<div className={classes.navBarContainer}>
<Tabs
centered
value={value}
variant="fullWidth"
onChange={handleChange}
className={classes.navBar}
>
<Tab color="textPrimary" icon={<HomeIcon />} />
<Tab color="textPrimary" icon={<ExploreIcon />} />
</Tabs>
</div>
);
};
I solved this in a much easier fashion (I was surprised this worked so well - maybe there's a problem I haven't found out). I'm using Router 6 and React 17 (I know these packages are newer).
In any case, I just used the useNavigate hook in the handleChange function. Thus, now there is NO need for Switch and the code becomes much simpler. See below:
let navigate = useNavigate();
const [selection, setSelection] = useState();
const handleChange = (event, newValue) => {
setSelection(newValue);
navigate(`${newValue}`);
}
return (
<Tabs value={selection} onChange={handleChange}>
<Tab label="Products" value="products" />
<Tab label="Customers" value="customers" />
<Tab label="Invoices" value="invoices" />
</Tabs>
);
}
The handleChange function updates 'selection' which controls the display of the tabs, and also navigates to the right path.
if you set the component somewhere in your React space, and set correctly a :style route (as explained by React Router: https://reactrouter.com/docs/en/v6/getting-started/overview), you can also control in which area of the page will the content be rendered. Hope it helps somebody!
I got it working this way in my app:
import React, {useEffect, useRef} from 'react';
import PropTypes from 'prop-types';
import {makeStyles} from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import Typography from '#material-ui/core/Typography';
import Box from '#material-ui/core/Box';
import Container from "#material-ui/core/Container";
import {Link} from "react-router-dom";
import MenuIcon from "#material-ui/icons/Menu";
import VideoCallIcon from "#material-ui/icons/VideoCall";
const docStyles = makeStyles(theme => ({
root: {
display: 'flex',
'& > * + *': {
marginLeft: theme.spacing(2),
},
},
appBarRoot: {
flexGrow: 1,
},
headline: {
marginTop: theme.spacing(2),
},
bodyCopy: {
marginTop: theme.spacing(1),
fontSize: '1.2rem',
},
tabContents: {
margin: theme.spacing(3),
},
}));
function TabPanel(props) {
const {children, value, index, classes, ...other} = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Container>
<Box className={classes.tabContents}>
{children}
</Box>
</Container>
)}
</div>
);
}
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
function TabOneContents(props) {
const {classes} = props;
return (
<>
<Typography variant="h4" component={'h1'} className={classes.headline}>
Headline 1
</Typography>
<Typography variant="body1" className={classes.bodyCopy}>
Body Copy 1
</Typography>
</>
)
}
function TabTwoContents(props) {
const {classes} = props;
const nurseOnboardingPath = '/navigator/onboarding/' + Meteor.userId() + '/1';
return (
<>
<Typography variant="h4" component={'h1'} className={classes.headline}>
Headline 2
</Typography>
<Typography variant="body1" className={classes.bodyCopy}>
Body Copy 2
</Typography>
</>
)
}
export default function MUITabPlusReactRouterDemo(props) {
const {history, match} = props;
const propsForDynamicClasses = {};
const classes = docStyles(propsForDynamicClasses);
const [value, setValue] = React.useState(history.location.pathname.includes('/tab_2') ? 1 : 0);
const handleChange = (event, newValue) => {
setValue(newValue);
const pathName = '/' + (value == 0 ? 'tab_1' : 'tab_2');
history.push(pathName);
};
return (
<div className={classes.appBarRoot}>
<AppBar position="static" color="transparent">
<Tabs value={value} onChange={handleChange} aria-label="How It Works" textColor="primary">
<Tab label="Tab 1" {...a11yProps(0)} />
<Tab label="Tab 2" {...a11yProps(1)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0} classes={classes}>
<TabOneContents classes={classes}/>
</TabPanel>
<TabPanel value={value} index={1} classes={classes}>
<TabTwoContents classes={classes}/>
</TabPanel>
</div>
);
}
...and in React Router:
[.....]
<Route exact path="/tab_1"
render={(routeProps) =>
<MUITabPlusReactRouterDemo history={routeProps.history}
/>
}/>
<Route exact path="/tab_2"
render={(routeProps) =>
<MUITabPlusReactRouterDemo history={routeProps.history} />
}/>
[.....]