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.
JavaScript
x
26
26
1
const GrandChild = ({ setParentInfo }) => {
2
const info = [1, 2, 3];
3
4
const handleClick = () => {
5
setParentInfo(info);
6
};
7
8
return <button onClick={handleClick}>Set parent info</button>;
9
};
10
11
const Sibling = ({ parentInfo }) => {
12
return <div>{parentInfo.length}</div>; // Do whatever you need with parentInfo
13
};
14
15
const Parent = () => {
16
const [parentInfo, setParentInfo] = useState([]);
17
18
return (
19
<div>
20
<GrandChild setParentInfo={setParentInfo} />
21
<Sibling parentInfo={parentInfo} />
22
</div>
23
);
24
};
25
26
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.