- Suppose I have a React class P, which renders two child classes, C1 and C2.
- C1 contains an input field. I’ll refer to this input field as Foo.
- My goal is to let C2 react to changes in Foo.
I’ve come up with two solutions, but neither of them feels quite right.
First solution:
- Assign P a state,
state.input
. - Create an
onChange
function in P, which takes in an event and setsstate.input
. - Pass this
onChange
to C1 as aprops
, and let C1 bindthis.props.onChange
to theonChange
of Foo.
This works. Whenever the value of Foo changes, it triggers a setState
in P, so P will have the input to pass to C2.
But it doesn’t feel quite right for the same reason: I’m setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.
Is this how I’m supposed to do it, or is there a more React-natural solution?
Second solution:
Just put Foo in P.
But is this a design principle I should follow when I structure my app—putting all form elements in the render
of the highest-level class?
Like in my example, if I have a large rendering of C1, I really don’t want to put the whole render
of C1 to render
of P just because C1 has a form element.
How should I do it?