import React from 'react'
import ReactDOM from 'react-dom'
import { useContext } from 'react'
const konteks = React.createContext(null);
function components(){
return(
<konteks.Provider value="hello world">
<MyComponent />
</konteks.Provider>
);
}
function MyComponent(){
const getcontext = useContext(konteks);
return(
<div>{getcontext}</div>
);
}
const body = ReactDOM.createRoot(document.getElementById("body"));
body.render(<MyComponent/>);
I already know the use of useContext, where we can pass data to other components,But I’m still confused regarding the implementation and the code above doesn’t error’ but just doesn’t work cause i thought it will print the hello world on the web browser.
Which part is wrong in my code?
2
Answers
You’re rendering
MyComponent
, notcomponents
(which would have the Provider), so the value of thekonteks
context isnull
.This is a official example:
App.js
Section.js
Heading.js
LevelContext.js
Hope you can understand.
Result: