Reactjs Another to pass data from child component to it grandparent(s) component without passing callback?

How to do this easily ? I uses Angular so I don't usually think about this problem as Angular does it automatically. in Angular, I can pass a variable from controller down to any "children" directive in any depth, and when that variable is changed, it permeates in all directives and controller who use it.

In React however, one must use callback which is then passed through layers of React component: passing data from child to parent component - react - via callback function.

I use the above solution to pass a single variable through 3 different React components :


EDIT: It is not that I don't understand how to pass the variable through layers of component. I just think there must be more easier way to do this.

I think this solution is quite complicated. Keep in mind that we usually deal with more than three "components" in the real life. Can someone give me suggestion of how to do this 'right' ?

I'm just learn React for a day now so I must miss something. Thank you

1 answer

  • answered 2018-01-14 11:39 Carlo

    If you want to pass a variable through many childs, the most correct way of doing it in React is just passing them through props.

    If you don't want to use this aproach you could use state management libraries like redux.

    If you want instead to do this using pure React you could use the component's context, although it is not recommended.

    See more about context here