Reputation: 2594
I've got a component like FeedSwitcher with two tabs inside
one for the general feed the other one only for the posts of the current user
in FeedSwitcher component at the start the value is 0 therefore the current user can view all the feed.
const FeedSwitcher = ({feed, posts, user }: FeedSwitcherProps) => {
const classes = useStyles();
const [value, setValue] = useState(0);
const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
setValue(newValue);
};
return (
<div className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
variant="fullWidth"
indicatorColor="primary"
textColor="primary"
aria-label="switcher tabs"
>
<Tab icon={<PeopleIcon />} aria-label="phone" />
<Tab icon={<PersonIcon />} aria-label="favorite" />
</Tabs>
<TabPanel value={value} index={0}>
<Feed feed={feed} />
</TabPanel>
<TabPanel value={value} index={1}>
<Posts posts={posts} user={user} />
</TabPanel>
</div>
);
};
After the current user post a new thread
(the form is in the parent component)
I want to show the tab with index 1
How can set the value from the parent?
Should I use a redux state or is there an other direct and simpler way?
Upvotes: 1
Views: 699
Reputation: 59
The state needs to be in the parent component.
You can feed the child component with the value, and pass it a function argument like onValueChange
that it can use to trigger an update on the parent's state.
// in parent
const [feedSwitcherValue, setFeedSwitcherValue] = useState(0);
return (
<FeedSwitcher
feed={feed}
posts={posts}
user={user}
value={feedSwitcherValue}
onValueChange={value => setFeedSwitcherValue(value)}
/>
);
// child
const FeedSwitcher = ({feed, posts, user, value, onValueChange }: FeedSwitcherProps) => {
const classes = useStyles();
const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
onValueChange(newValue);
};
return (
<div className={classes.root}>
<Tabs
value={value}
onChange={handleChange}
variant="fullWidth"
indicatorColor="primary"
textColor="primary"
aria-label="switcher tabs"
>
<Tab icon={<PeopleIcon />} aria-label="phone" />
<Tab icon={<PersonIcon />} aria-label="favorite" />
</Tabs>
<TabPanel value={value} index={0}>
<Feed feed={feed} />
</TabPanel>
<TabPanel value={value} index={1}>
<Posts posts={posts} user={user} />
</TabPanel>
</div>
);
};
Upvotes: 1