Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React tutorial: Uncaught TypeError: Cannot read property 'data' of null

I'm following React tutorial at: http://facebook.github.io/react/docs/tutorial.html

I'm just after http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server

I went through similar questions on SO but not found a solution for my specific case.

var data = [
    {author: "Pete Hunt", text: "This is one comment"},
    {author: "Jordan Walke", text: "This is *another* comment"},
    {author: "Bob Lilly", text: "This is *another* comment 2"}

];

var Comment = React.createClass({
    render: function() {
        var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
        return (
            <div className="comment">
                <h2 className="commentAuthor">
                    {this.props.author}
                </h2>
                <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
            </div>
        );
    }
});

var CommentList = React.createClass({
    render: function() {
        var commentNodes = this.props.data.map(function (comment) {
            return (
                <Comment author={comment.author}>
                    {comment.text}
                </Comment>
            );
        });
        return (
            <div className="commentList">
                {commentNodes}
            </div>
        );
    }
});

var CommentForm = React.createClass({
    render: function() {
        return (
            <div className="commentForm">
                <br/>Hello, world! I am a CommentForm.
            </div>
        );
    }
});

var CommentBox = React.createClass({
    render: function() {
        return (
            <div className="commentBox">
                <h1>Comments</h1>
                <CommentList data={this.props.data} /> 
                <CommentForm />
            </div>
        );
    }
});


React.render(
    // <CommentBox url="comments.json" />, 
    <CommentBox data={data} />,
    document.getElementById('content')
);

When I try to use data got from server (first step --> see 2nd link), I get this error:

Uncaught TypeError: Cannot read property 'data' of null

I guess this has something to do with passing data the wrong way.

EDIT: I edited the cod with the answers given so far

EDIT 2: Now it works with dumb data (var data = [ ... ) but not when got from the server

like image 486
dragonmnl Avatar asked Sep 09 '15 21:09

dragonmnl


1 Answers

You're sending data as a prop to CommentBox and trying to pass it on through CommentBox state.

<CommentList data={this.props.data} />

instead of

<CommentList data={this.state.data} />

I usually reason about props this way; Props are stuff coming in and State is stuff that's already in.

like image 64
Henrik Andersson Avatar answered Nov 03 '22 08:11

Henrik Andersson