Reputation: 477
I am developing my first React app and am currently facing the problem that data has to be exchanged between several components at runtime. I have found various approaches to this, but am totally confused as to which one I should follow and which one makes the most sense.
Requirement 1: Send data from the parent component to the child component (while running)
Data should be sent from the parent component to a child component. This could be, for example, the content of an input field. I currently use the reference API for this. In the parent component I have created a reference to the child component and call the function (with parameters) of the child component using a callback (onChange).
const map = useRef();
[...]
<Map ref={map} />
[...]
<input type="text" placeholder="Enter location" onChange={enterLocation} />
[...]
function enterLocation(event) {
map.current.locationSearch(location); // Function of the child component
}
Requirement 2: Send data from the child component to another child component (while running)
Data is to be sent between two child components. I have found various approaches to this: Redux, Context API and also the Reference API. My idea is to first send the data to the parent component and then send it on to the other child component via a reference. However, this seems unnecessarily complicated to me.
Upvotes: 0
Views: 387
Reputation: 391
Usually the simplest solution is the best.
for first example you can send data from parent component to children component as props:
function Parent() {
const data = 'some_string';
return <div>
<Child title={data} />
<div>Other component</div>
</div>
}
function Child(props) {
return <span>{props.title}</span>
}
for second requirement you can use state, if two children use some state, you can up this state in parent:
function Parent() {
const [state, setState] = useState('');
return <>
<Input value={state} setValue={setState} />
<Length str={state} />
</>
}
function Input(props) {
return <input value={props.value} onChange={(e) => props.setValue(e.target.value)} />;
}
function Length(props) {
return <div>You insert string with length: {props.str.length}</div>
}
Upvotes: 2