I have several child components:
const Type = () => {
const initialState = {
cat: false,
dog: false,
parrot: false,
hamster: false,
}
const [type, setType] = useState(initialState);
const clearFilters = () => {
setType(initialState);
}
}
const Age = () => {
const initialAutoAgeState = [
{name: 'baby', selected: false},
{name: 'young', selected: false},
{name: adult, selected: false},
]
const initialManualAgeState = {
start: '',
end: '',
}
const [autoAge, setAutoAge] = useState(initialAutoAgeState);
const [manualAge, setManualAge] = useState(initialManualAgeState);
const clearFilters = () => {
setAutoAge(initialAutoAgeState);
setManualAge(initialManualAgeState);
}
}
const Color = () => {
const initialState = [{color: 'brown'}];
const [color, setColor] = useState(initialState);
const clearFilters = () => {
setColor(initialState);
}
}
They all have their own states and conditions for controlling that state.
I also have a parent component which will accept one of the children:
const Container = ({children}) => {
const [value, setValue] = useState([]);
return(
<>
{React.cloneElement(children,{callback={setValue})}
<Button onClick={/**Make it trigger clearFilters in child element**/}>Clear all</Button>
</>
)
}
It will be used together as:
<Container><Type/></Container>
<Container><Age/></Container>
<Container><Color/></Container>
clearFilters
is a part of child component since it needs to do something different in each child. But I need to trigger execution of this function by pressing button that's located in parent component. How it can be done? I can't just use function from parent and pass it into child/button.