I am trying to create a UserContext to be accessible to all class components in the React app. I am receiving the following error.
ReferenceError: Cannot access 'UserContext' before initialization
App.js
import React, { createContext } from 'react';
export const UserContext = createContext(null);
function App() {
return (
<div className="App">
<UserContext.Provider value={null}>
<PageRoutes />
</UserContext.Provider>
</div>
);
}
export default App;
LoginPage.js
import React, { Component } from 'react';
import { UserContext } from './App';
class MasterLoginPage extends Component {
static contextType = UserContext;
constructor(props) {
super(props);
this.state = {
username: null,
loggedIn: false
}
// logic to work with username, password authentication
render() {
return (
<div>
// logic for rendering login page
{
this.state.loggedIn &&
<UserContext.Provider value={this.state.username} />
}
</div>
}
}
MasterLoginPage.contextType = UserContext;
export default MasterLoginPage;
PageRoutes.js
import React from 'react';
export default () => (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={LoginPage} />
<Route exact path="/home" component={Home}/>
</Switch>
</BrowserRouter>
);
Home.js
import React from 'react';
export default class Home extends React.Component {
// I want to put this user in a state variable in this component
}
- Why am I getting reference error as I have already defined it in App.js ?
- If I have to store the userContext value in a state variable in some other class component say Home.js then how do I do that ?