Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS this.state null

Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link data that will be looped through with map.

I have tried setting it as the components state then passing it to the navbar links via a prop but I am getting "Uncaught TypeError: Cannot read property 'data' of null"

I tried to look around for solutions but could not find anything.

Note: When I try to hard code an object and map through it that way it returns map is undefined. However I am not sure that is directly related to the setState error.

/** @jsx React.DOM */

var conf = {
    companyName: "Slant Hosting"
  };

var NavbarLinks = React.createClass({
  render: function(){
    var navLinks = this.props.data.map(function(link){
      return(
        <li><a href={link.target}>{link.text}</a></li>
      );
    });
    return(
      <ul className="nav navbar-nav">
        {navLinks}
      </ul>
    )
  }
});

var NavbarBrand = React.createClass({
  render: function(){
    return(
      <a className="navbar-brand" href="#">{conf.companyName}</a>
    );
  }
});

var Navbar = React.createClass({
  getInitalState: function(){
    return{
      data : []
    };
  },
  loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        this.setState({
          data: data
        });
        console.log(data);
        console.log(this.state.data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function(){
    this.loadNavbarJSON();
  },
  render: function(){
    return(
      <nav className="navbar navbar-default navbar-fixed-top" role="navigation">
        <div className="container-fluid">
          <div className="navbar-header">
            <NavbarBrand />
          </div>
          <NavbarLinks data={this.state.data} />
        </div>
      </nav>
    );
  }
});

var Header = React.createClass({
  render: function(){
    return(
      <Navbar />
    );
  }
});

React.renderComponent(
  <Header />,
  document.getElementById('render')
);
like image 296
Matthew Wisniewski Avatar asked Oct 16 '14 15:10

Matthew Wisniewski


People also ask

Why is state empty React?

Empty state in ReactBecause our data is coming from a server, we can't know for sure if there will be data at all. We might receive an empty list. If this happens with our current implementation, the user will only see the Table headers, which will be pretty confusing.

How do you check if a React is null?

To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run.

What is null in React?

When you say null means you are not passing any props to that component. ~~ type in React. createElement can be a string like h1 , div etc or a React-Component. var reactElement = React.


3 Answers

Using ES6, the initial state must be created in your constructor for the React component class, like this:

constructor(props) {
    super(props)
    this.state ={
    // Set your state here
    }
}

See this documentation.

like image 68
yussan Avatar answered Oct 19 '22 09:10

yussan


This question has already been answered, but I came here by having a problem that can easily happen to anyone.

I was getting a console.log(this.state) to log null in one of my methods, just because I didn't write:

this.handleSelect = this.handleSelect.bind(this);

in my constructor.

So, if you're getting a null for this.state in one of your methods, check if you have bounded it to your component.

Cheers!

Edit (because of @tutiplain's question)

Why was I getting null for this.state?

Because I wrote console.log(this.state) in the method which wasn't bounded to my class (my handleSelect method). That caused this to point to some object higher in the object hierarchy (most probably the window object) which doesn't have a property named state. So, by binding my handleSelect method to this, I assured that whenever I write this in that method, it will point to the object in which the method is in.

I encourage you to read a really good explanation for this here.

like image 20
Filip Savic Avatar answered Oct 19 '22 09:10

Filip Savic


this.state.data is null in your example because setState() is async. Instead you can pass a callback to setState like so:

loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        console.log(data);

        this.setState({data: data}, function(){
          console.log(this.state.data);
        }.bind(this));

      }.bind(this),
    });
  }

https://facebook.github.io/react/docs/component-api.html#setstate

like image 11
Blair Anderson Avatar answered Oct 19 '22 10:10

Blair Anderson