0

Say in the current project, we don't have redux set up. we have these components in hierarchy:

- p1
-- p2
--- p3
---- p4
----- c1

I want p3 component to change c1's states and c1 changes p3's states. Is there an easy way to achieve this?

kenpeter
  • 7,404
  • 14
  • 64
  • 95
  • possible duplicates of [sharing state](https://stackoverflow.com/questions/38901106/how-to-make-a-shared-state-between-two-react-components) and [accessing child state](https://stackoverflow.com/questions/27864951/how-to-access-childs-state-in-react). Also see react docs about [lifting state](https://reactjs.org/docs/lifting-state-up.html) – Eric Ren Nov 19 '18 at 04:26
  • @Eric Ren ok, so you are saying I need to keep passing function from parent to child component, if it is very deep. Use ref to do the opposite? – kenpeter Nov 19 '18 at 04:34

1 Answers1

0

Changing C1's state from P3:

The p3 component can change c1's state by changing the props it passes down to p4 which must change the props it passes down to c1. In c1 you will detect the prop change via componentWillReceiveProps and in this function set your new c1 state from the props that were passed down all the way from p3:

// in c1
componentWillReceiveProps(newProps) {
    this.setState({ someC1Data: newProps.someP3Data });
}

Changing P3's state from C1:

This can be accomplished through the use of callbacks. The props of c1 will be a callback, say changeParent3State(someC1Data), so in c1 you would call this.props.changeParent3State(someC1Data) whenever you wanted to change p3's state. You would have the same function callback in p4 such that p4 receives c1's function call and p4 makes the same call up the parent tree to p3 via this.props.changeParent3State(someC1Data) again. The p3 component has now received c1's data and in the function implementation can change its state based on the c1's data, if any data was given:

// in p3
changeParent3State(someC1Data) {
    this.setState({ someP3Data: someC1Data});
}
Shawn Andrews
  • 1,432
  • 11
  • 24