Hello i have an array called info[] in a grandchild component and i want my parent component when a button is clicked to access the array. I also want a sibling component to have access to it. How is this possible .. i am a bit confused. Should I use use-context ?
Thank you!
Advertisement
Answer
If I have understand what you are asking it could be something like this.
const GrandChild = ({ setParentInfo }) => { const info = [1, 2, 3]; const handleClick = () => { setParentInfo(info); }; return <button onClick={handleClick}>Set parent info</button>; }; const Sibling = ({ parentInfo }) => { return <div>{parentInfo.length}</div>; // Do whatever you need with parentInfo }; const Parent = () => { const [parentInfo, setParentInfo] = useState([]); return ( <div> <GrandChild setParentInfo={setParentInfo} /> <Sibling parentInfo={parentInfo} /> </div> ); };
Here you don’t need context because you don’t have that much layers but if you need to drill down the props than use a context.