I have a SortSelect(child) component that I want to put in my Home(parent) component.
export default function SortSelect() {
const classes = useStyles();
const [sortType, setSortType] = useState('asc');
const handleChange = (event) => {
setSortType(event.target.value);
};
return (
<FormControl className={classes.formControl}>
<Select
value={sortType}
onChange={handleChange}
displayEmpty
className={classes.selectEmpty}
inputProps={{ 'aria-label': 'Without label' }}
>
<MenuItem value='asc'>Count asc</MenuItem>
<MenuItem value='desc'>Count desc</MenuItem>
<MenuItem value='a-z'>Name A-Z</MenuItem>
<MenuItem value='z-a'>Name Z-A</MenuItem>
</Select>
<FormHelperText>Sort by</FormHelperText>
</FormControl>
);
}
I need to get SortSelect's sortType state, so I can sort my array. How can I do this?
That really doesn't sound like a pattern that you should implement with React. If the parent component needs that state, then it should handle it and pass the state as a prop to SortSelect.
If it needs the sortType only momentarily instead of having it in its state, then you could simply pass a callback from Home to SortSelect that's called in SortSelect's handleChange function.
Just as a note, it is possible to expose state to a parent component using React's useImperativeHandle hook, but you really shouldn't use that unless you are 100% sure of what you're doing.