Object literal values and React.js

4.4k views Asked by At

Lets say there are 2 components Main and Card, Card is child of Main in React.js. Card will pass in an string value to Main. Thus state in Main for the Card would update.

var Card= React.createClass({
...
this.props.updateName(loginVal.value); //pass in a 'string' to updateName()
...
});

var Main = React.createClass({
    getInitialState: function() {
        return {
            names: []
        };
    },
    updateName: function (loginVal) {
        this.setState({ 
            names: this.state.names.concat(loginVal) // I don't understand why using 'concat' works but not 'push'.
        });
    },
    render: function(){
        var cardArr = this.state.names.map(function(item){
            return ( <Card login={item} /> );
        });
        return (
            <div>
                <Form updateName={this.updateName} />
                {cardArr}
            </div>
        );
    }
});

My question is why this.state.names.concat(loginVal) works when this.state.names is an empty array and loginVal is a string. [].concat('string') just don't make sense to me.

2

There are 2 answers

6
Oden On BEST ANSWER

push adds the provided element(s) and returns the new length of the array, so this.state.names would be a number.

concat adds the provided element(s) to a new array and returns it, so this.state.names would be an array with the new name added.

3
marcel On

[].concat(["string", "other string") will push each value to an new empty array. You can also pass a simple string instead of an array because the method was overwritten to make it more flexible.

push("string") do not work because it will return the new length of the array. But it will change the array instead of creating a new one.

you could use this:

this.state.names.push(value);
this.setState({
    names: this.state.names
});