React : Context Concepts
When a parent component contains of many inner child components ,which share data that needs to be globally accessed.
React context comes into picture
Context , It is designed to share global data for a tree of react components.
To begin, we need to create a context as first step:
React context comes into picture
Context , It is designed to share global data for a tree of react components.
To begin, we need to create a context as first step:
const FontName = React.createContext("sans-serif")
We use createContext Function for this.
Inside class we need to wrap the app in a provider with a value. Also this approach only works with class-based components.
In the child component, which needs the font name will be retrieved as below:
<Font.Name.Provider value={"calibri"}>
<Header/>
<Content/>
<Footer/>
</Font.Name.Provider>
In the child component, which needs the font name will be retrieved as below:
Class Title extends React.Component{
render(){
const font = this.context
return(
<div className = {`${font}-f`}>
//page title
</div>
)
}
}
If we are using functional components, then need to use FontName.Consumer to pass info to the app
ie, we need to wrap elements in <FontName.Consumer>
ie, we need to wrap elements in <FontName.Consumer>
function Title(){
return(<FontName.Consumer>{font =>(<div className = {`${font}-f`}>//page title</div>)}</FontName.Consumer>)}
Comments
Post a Comment