Posts Simple use of react context
Post
Cancel

Simple use of react context

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;

Demo

This post is licensed under CC BY 4.0 by the author.