'ReactJS, passing data between siblings
Can someone, please, point me in the right direction?
I have 3 components in my app.jsfile:
componentA
componentB
componentC
I guess they are siblings, no parent/child relationships here.
Components A and B are 2 input forms. Both inputs are for numbers (3 digit numbers).
Component C is the button.
Once I click on the button I need to get input values from components A and B (so would be 2 numbers), do some if/else statements and return some result.
My question is what's the best way to pass data from components A and B into the C?
Solution 1:[1]
As the React doc says, if two components need to have access to the same state, the solution is to put the state in the closest common ancestor.
In the case of your form, the button needs to read the states from each input to submit the form. So each input's state should be in the parent of the button and the two inputs.
Here is one example :
const Form = () => {
const [value1, setValue1] = useState('')
const [value2, setValue2] = useState('')
return (
<>
<Input value={value1} onChange={event => setValue1(event.target.value)}/>
<Input value={value2} onChange={event => setValue2(event.target.value}}/>
<SubmitButton onClick={() => submit({value1, value2})}/>
</>
)
}
If you need to pass input values through too many props, you can use a context, a state management library (zustand, jotai, ...) or a form library (Formik, react-hook-form, ..).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emmanuel Meric de Bellefon |
