Posted May 5, 2020 2020-05-05T15:28:00+02:00 by Karl Sandin
Updated May 12, 2020 2020-05-12T15:58:59+02:00
Simple use of react context, useful instead of passing props through multiple components AKA Prop Drilling. In this example we pass a value down from Parent.js
to Child.js
and send a click event back from Child.js
to Parent.js
.
MyContext.js
1
2
3
4
5
6
| import React from "react";
const MyContext = React.createContext(null);
export default MyContext;
|
Parent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| import React from "react";
import MyContext from "./MyContext.js";
import Child from "./Child.js";
const Parent = () => {
const onClick = () => {
alert("Clicked!");
};
return (
<MyContext.Provider value={ { someValue: "Value send from parent", onClick: onClick } }>
<Child />
</MyContext.Provider>
);
};
export default Parent;
|
Child.js
This can be a child component nested several levels under Parent.js, but still has access to Parent.js props due to <MyContext.Consumer>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| import React from "react";
import MyContext from "./MyContext.js";
const Child = () => {
return (
<MyContext.Consumer>
{({ onClick, someValue }) => (
<div>
<span>{someValue}</span>
<br />
<button onClick={() => onClick()}>Click me!</button>
</div>
)}
</MyContext.Consumer>
);
};
export default Child;
|