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
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>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With