Functional Components
Component where the context is defined and which provides the actual component with the context.
const functionalComponent = () => {
...
return(
<>
<contextName.Provider value = "contextValue">
<ComponentThatUsesTheContext />
</contextName.Provider>
</>
)
}
Component where the context is to be used (uses useContext hook)
const ComponentThatUsesTheContext = () => {
const {contextUser} = useContext(contextName);
...
return(
<>
{contextUser}
</>
)
}
Class Components
Creating context
const contextName = React.createContext();
const contextProvider = contextName.Provider;
const contextConsumer = contextName.Consumer;
export {contextProvider , contextConsumer }
Component where the context is defined and which provides the actual component with the context.
import contextProvider;
class classComponent extends React.Component{
render(){
return(
<>
<contextProvider value = "contextValue">
<ComponentThatUsesTheContext />
</contextProvider>
</>
)
}
}
consumer ->
import contextProvider;
class ComponentThatUsesTheContext extends React.Component{
render(){
return(
<>
<contextConsumer>
{(contextTaken) => {
return(
<>
contextTaken
</>
)
}
}
</contextConsumer>
</>
)
}
}
Top comments (0)