2

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.

Alyona
  • 1,682
  • 2
  • 21
  • 44
  • maybe this link will help you https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children – zahra zamani Dec 01 '21 at 13:55
  • Unfortunately, child components are more complex than here and can't be just cloned with shared function. What I'm looking for is a way to trigger child function from parent (pressing button inside parent) – Alyona Dec 01 '21 at 14:44

0 Answers0