0

I have a parent Container, I plan to pass inside different child components that will accept callback.

Container:

const Container = ({children}) => {
   const [selection, setSelection] = useState([]);

   const setSelection = (returnObject) => {
      setSelection(prev => [...selection, returnObject])
   }

   return(
      <StyledContainer>
         {children}
         <Button>Search {selection}</Button>
      </StyledContainer>
   )
}

Container will have different children that all accept callback:

<Container><Child1 callback={}></Container>
<Container><Child2 callback={}></Container>
<Container><Child3 callback={}></Container>

Is there a way to pass component as a child to Container and for that Child to be using setSelection function as prop for Child's callback prop? (without Redux)

Alyona
  • 1,682
  • 2
  • 21
  • 44
  • `setSelection` having a function with same name as state update function will lead to an error. – Himanshu Singh Nov 30 '21 at 17:36
  • First of all, your react code is incorrect. You have `setSelection` coming from `useState` then you are defining a const with same name `setSelection` on the next line, that is invalid code. – Arpit Nov 30 '21 at 17:37
  • This issue has already been answered https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children You can refer to this. I hope this resolves your query. – Himanshu Singh Nov 30 '21 at 17:39
  • You can pass components as children, react components accept children as props and you can access the children as `props.children` in your parent component. Here's a StackOverflow answer for you: [https://stackoverflow.com/a/39655113/13901135](https://stackoverflow.com/a/39655113/13901135) – Arpit Nov 30 '21 at 17:39

1 Answers1

0

Yes you can override any props passed to the children as follows:

const Container = ({children}) => {
   const [selection, setSelection] = useState([]);

   const setSelection = (returnObject) => {
      setSelection(prev => [...selection, returnObject])
   }

   return(
      <StyledContainer>
         {React.cloneElement(children, {callback: setSelection } }
         <Button>Search {selection}</Button>
      </StyledContainer>
   )
}

Then you can use it as:

<Container><Child1/></Container>
<Container><Child2/></Container>
<Container><Child3/></Container>

And inside of each Child component, you can call callback() as need it.

React.cloneElement will create a copy from children passing additional props in this case only callback is passed as a prop you can pass as many as you need as a new object.

Details: https://reactjs.org/docs/react-api.html#cloneelement

Crisoforo Gaspar
  • 3,740
  • 2
  • 21
  • 27