1

I'm having a bit of trouble figuring out a way to pass along props to a component's children. What I would like to do is have a component (ParentComponent) that has a function (toggleSuccess()) that alters its own state (eg a boolean called success) and pass that function down as an onClick prop to all of its children. Ideally I could then put all kinds of components into ParentComponent, and they would all gain access to toggleSuccess() through their onClick prop. Is there a way to do this that doesn't involve any sloppy global variables, or require some central state management like redux? Thanks!

David C
  • 64
  • 2
  • 9
  • https://reactjs.org/docs/context.html#when-to-use-context and https://reactjs.org/docs/context.html#before-you-use-context – nem035 Mar 05 '19 at 21:17
  • @nem035 Sorry, I meant to emphasize NOT using global variables. Looks like I asked a duplicate question anyway. – David C Mar 05 '19 at 22:32

1 Answers1

0

Events bubble up, so you could just catch all click events in the parent instead of passing the handler down:

 class ParentComponent extends React.Component {
  //...
  toggleSuccess() { /*...*/ }
  //...
  render() {
    const { children } = this.props;
    return (
      <div onClick={() => this.toggleSuccess()} >
       {...children}
      </div>
     );
   }
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Thanks Jonas, that was going to be my backup plan. It looks like using React.Children and cloneElement will be the more elegant solution. Cheers! – David C Mar 05 '19 at 22:30