M
M
Muranx2022-04-01 12:48:50
React
Muranx, 2022-04-01 12:48:50

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')
);

This example works, but of course "child components" will be larger (in terms of code volume) and keeping all of them in one file is not realistic, so what to do? In the global scope in the example above, I can write to the child farthest from the top of the tree static contextType = Context;and it will find it easily, because the variable Contextis in the global scope, BUT if all the children are separated into files, we will not be able to access this variable Contextin 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

1 answer(s)
M
Mashush, 2022-04-01
@Muranx

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')

later in the child component write:
import {ParentContext} from '...'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question