Answer the question
In order to leave comments, you need to log in
How to correctly pass context between files in react?
Hello, newbie question in react!
I'm trying to figure out how to pass the context in React through several children, but everywhere in the articles there is an example where all components are created in the global scope, and there is access to a variable containing the context, as in the example below ..
var Context = React.createContext('123');
class FirstComponent extends React.Component{
render(){
return (
<SecondComponent />
)
}
};
class SecondComponent extends React.Component{
render(){
return (
<ThirdComponent />
)
}
};
class ThirdComponent extends React.Component{
static contextType = Context;
render(){
return <h1>{this.context.greetings}</h1>; // Ola
}
};
ReactDOM.render(
<Context.Provider value={{greetings: 'Ola'}}>
<FirstComponent />
</Context.Provider>,
document.getElementById('root')
);
static contextType = Context;
and it will find it easily, because the variable Context
is in the global scope, BUT if all the children are separated into files, we will not be able to access this variable Context
in the file with the child furthest from the top ... How to be? Pass the state through props, well, this is clearly not an option. the context is partly and created not to pass props through 10 children, maybe I wasn’t attentive somewhere, or I wasn’t looking well enough, in any case, this is an easy solution for you, if you tell me of course!
Answer the question
In order to leave comments, you need to log in
So here in the official React documentation it is written how to pass context between components. Moreover, it is said both about class components (ParentContext.Provider => ParentContext.Consumer), and about functional ones (ParentContext.Provider => useContext(ParentContext).
Just export the context itself from the parent component:
export const ParentContext = React.createContext('123')
import {ParentContext} from '...'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question