AtanasB
AtanasB

Reputation: 160

React createContext throwing errors

I'm trying to learn React context API. I am trying to create a context with a default value of green, later changed to red by the context provider. The error I get is "value is not defined". Trying to temporarily fix the issue by providing constant color I get a render error. How to make this code successfully use context API and pass the color?

import React from "react";
import "./styles.css";
const Counter = React.createContext("green");

export default function App() {
  return (
    <>
      <Counter.Provider value={"red"}>
        <Counter.Consumer>
          <div className="App">
            <h1 style={{ color: value }}>Hello World!</h1>
          </div>
        </Counter.Consumer>
      </Counter.Provider>
    </>
  );
}

P.S. I tried implementing React.useContext instead of just passing value but reference error was thrown printing that "value" is not defined.

Codesandbox: https://codesandbox.io/s/suspicious-buck-xvvlf?file=/src/App.js

Upvotes: 0

Views: 1356

Answers (1)

AKX
AKX

Reputation: 168834

As the docs say, the context consumer accepts a "render prop" style function as a child.

import React from "react";
import "./styles.css";
const Counter = React.createContext("green");

export default function App() {
  return (
    <>
      <Counter.Provider value={"red"}>
        <Counter.Consumer>
          {(value) => (  // <-- new
            <div className="App">
              <h1 style={{ color: value }}>
                Hello World!
              </h1>
            </div>
          )}
        </Counter.Consumer>
      </Counter.Provider>
    </>
  );
}

Upvotes: 3

Related Questions