React state - what I am doing wrong?

- 1 answer

Ad

I am trying to learn reactjs and building small app that takes in names and then shows the names..

I have an input form, and I am able to get data from input form after clicking submit into my state object called names.

however I am stuck on passing the state from the parent to another component that is inside of my ShowNames component:

So, in App, I am doing this render:

render : function() {
        return (
            <div>
                <InputName addToState={this.addToState}/>
                <ShowName renderName={this.renderName}/>
            </div>
        )
    }
});

Then ShowName component has following:

var ShowName = React.createClass({

    render : function() {
        return (
            <ListOfNames renderName={this.props.renderName}/>
        )
    }
});

So I made

var ListOfNames = React.createClass({

    render : function() {
        return (
            <ul renderName={this.props.renderName}>
                {Object.keys(this.state.names).map(this.renderName)}
            </ul>
        )
    }
});

But the issue is it says Cannot read property 'names' of null. Can someone help?

Ad

Answer

Ad

You need to initialise the state otherwise the state will be null.

React.createClass({
    getInitialState: function() {
        return { names: [] };
    },

    // all the rest here
}

EDIT

after seeing the code I noticed a couple of errors, the updated code is now here: http://jsbin.com/sewoxu/edit?js,output

So what the main error was that the render function of ShowName was using the state to get the names, but the names where passed via property:

<ShowName renderName={this.renderName} names={this.state.names}/>

so in this case to access the names attribute you need to do:

this.props.names

Also in the example I have moved the renderName function inside the ShowName component.

Hope this helps :)

Ad
source: stackoverflow.com
Ad