Melissa Stewart
Melissa Stewart

Reputation: 3625

TypeError: Cannot read property <parameter> of null while passing data in React

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

Answers (2)

mostafa tourad
mostafa tourad

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

react state and life cycles

component state FAQ

understanding react.js state

Upvotes: 2

Chaim Friedman
Chaim Friedman

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

Related Questions