Reputation: 7755
I have a several tabs in my react app and i only wanted to load that specific tab when i click it.
Right now, my problem is that other tabs is also rendering when i click a specific tab. I have use console.log
to see if other tabs is rendering and is really is. How can i prevent that from happening. I wanted to load a tab only when i click it.
Pls see my codesandbox here: CLICK HERE
<div>
<AppBar position="static" color="inherit" className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs example"
>
<Tab label="Users" component={Link} to="/users" {...a11yProps(0)} />
<Tab
label="Products"
component={Link}
to="/products"
{...a11yProps(1)}
/>
<Tab label="Sales" component={Link} to="/sales" {...a11yProps(2)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
<Users />
</TabPanel>
<TabPanel value={value} index={1}>
<Products />
</TabPanel>
<TabPanel value={value} index={2}>
<Sales />
</TabPanel>
</div>
Upvotes: 0
Views: 2224
Reputation: 14891
You should separate the task of getting tab value from pathname into a separated utility function. Because when you switch between tab, value is set, trigger handleChange
and then cause the pathname to be changed, which also result in function in useEffect
(you use to get tab value from pathname) is also triggered too, result in unexpected behavior
const getTabFromPathname = (pathname) => {
switch (pathname) {
case "/users":
return 0;
case "/products":
return 1;
case "/sales":
return 2;
default:
return 0;
}
};
function TabComponent(props) {
const classes = useStyles();
const [value, setValue] = React.useState(
getTabFromPathname(props.history.location.pathname)
);
const handleChange = (event, newValue) => {
setValue(newValue);
};
// ...
}
Below is forked codesandbox for fixes
Upvotes: 3