Reputation: 3625
I'm new to React, thus the question. This is my App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {loggedIn: false}
}
render() {
return (
<div>
<Helmet>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
</Helmet>
<Wrapper state={this.state.loggedIn}/>
</div>
)
}
}
export default App;
I'm trying to pass the state to Wrapper component.
class Wrapper extends React.Component {
render() {
const MainComp = this.state.loggedIn ? CoreLogged : CoreUnlogged;
return (
<BrowserRouter>
<div className="wrapper">
<Header state={this.state.loggedIn}/>
<MainComp />
</div>
</BrowserRouter>
);
}
}
export default Wrapper;
I get the following error,
TypeError: Cannot read property 'loggedIn' of null
What am I doing wrong here?
Upvotes: 1
Views: 360
Reputation: 4388
in Wrapper component edit your render method to use this.props.state not this.state because you pass a prop named state to the component not in the instance and at the same time the state prop is a Boolean not and object edit your code to be something like this
class Wrapper extends React.Component {
render() {
const MainComp = this.props.state? CoreLogged : CoreUnlogged;
return (
<BrowserRouter>
<div className="wrapper">
<Header state={this.props.state}/>
<MainComp />
</div>
</BrowserRouter>
);
}
}
export default Wrapper
if you're trying to make use of the state in the component you need to initialize the state in the constructor function
learn more here
Upvotes: 2
Reputation: 6263
In your render method here
render() {
const MainComp = this.state.loggedIn ? CoreLogged : CoreUnlogged;
return (
<BrowserRouter>
<div className="wrapper">
<Header state={this.state.loggedIn}/>
<MainComp />
</div>
</BrowserRouter>
);
}
You need to change this.state.loggedIn
to this.props.state.loggedIn
since you are passing down via props to wrapper component.
I would also suggest not calling the prop state.
Upvotes: 1