How to pass data between React Components
Data handling in React is not as complicated as it might seem. Hope you have gone through react docs where they have class components without typescript.
My examples here will be using typescript with functional react components.
It’s been recommended to lift the shared state up to their closest common ancestor.
Let’s assume we have a parent and 2 child components. One child provides data and another child consumes it.
Code:
Let’s start with the Consumer which requires data.
export type ConsumerChildPropType = {name: string};export function ConsumerChild(props: ConsumerChildPropType) {
return (
<>
<h1>{props.name}</h1>
</>
);
}
Next, We define another child which provides data.
export function ProducerChild(prop: {onStateChange: (name: string ) => void}) {
let [name, setName] = useState('');
useEffect(() => {
prop.onStateChange(name);
}, [name]);
return (<>
<input type='text' onChange={(t) => setName(t.target.value) }/>
</>);
}
Finally, we have Parent which holds ProducerChild and ConsumerChild and transfers data from one component to another.
export function Parent() {
let [name, setName] = useState('');
function nameChange(newName: string) {
setName(newName);
}
return (
<>
<ConsumerChild name={name}/>
<ProducerChild onStateChange={nameChange}/>
</>
);
}