Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass context between siblings using context in React

I have the following code where I am trying to get a value from one component to its sibling using the context api.

import React from "react";
import ReactDOM from "react-dom";

function App() {
  return (
    <div>
      <TheButton />
      <Display />
    </div>
  );
}

export const NumberContext = React.createContext();

function TheButton() {
  return (
    <NumberContext.Provider value={"test"}>
      <button>Click me</button>
    </NumberContext.Provider>
  );
}

function Display() {
  const context = React.useContext(NumberContext);
  return <div>The answer {context}.</div>;
}

ReactDOM.render(<App />, document.querySelector("#root"));

As you can see I am passing the 'test' value in the provider, but when the page renders all I see is "The answer ."

Here is a a codesandbox for the issue https://codesandbox.io/s/pedantic-forest-zjlc2

like image 903
AngularDebutant Avatar asked Oct 17 '25 03:10

AngularDebutant


1 Answers

Despite the fact that context gives you a decoupled way of passing props the Provider still must be on a higher hierarchy. Provide your context from your App and consume it from children.

export const NumberContext = React.createContext();

function App() {
    const [foo, changeFoo] = useState('foo')
    return (
        <NumberContext.Provider value={{ foo, changeFoo }}>
            <TheButton />
            <Display />
        </NumberContext.Provider>
    );
}


function TheButton() {
    const { changeFoo } = useContext(NumberContext)
    return (
        <button onClick={() => changeFoo('bar')}>Click me</button>
    );
}

function Display() {
    const context = React.useContext(NumberContext);
    return <div>The answer {context.foo}.</div>;
}
like image 113
Dupocas Avatar answered Oct 18 '25 17:10

Dupocas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!