Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, adding components in component

Tags:

reactjs

I started to learn React and I hit first wall.

I have a list component which should display a list of rows + button for adding a new row.

All is in those 2 gists:

https://gist.github.com/matiit/7b361dee3f878502e10a

https://gist.github.com/matiit/8bac28c4d5c6ce3993c7

The addRow method is executed on click, because I can see the console.log, but no InputRows are added.

Can't really see why.

This is a little updated (dirty) code which doesn't work either. Now it's only one file:

var InputList = React.createClass({

    getInitialState: function () {
        return {
            rowCount: 1
        }
    },

    getClassNames: function () {
        if (this.props.type === 'incomes') {
            return 'col-md-4 ' + this.props.type;
        } else if (this.props.type === 'expenses') {
            return 'col-md-4 col-md-offset-1 ' + this.props.type;
        }
    },

    addRow: function () {
        this.state.rowCount = this.state.rowCount + 1;
        this.render();
    },

    render: function () {
        var inputs = [];
        for (var i=0;i<this.state.rowCount; i++) {
            inputs.push(i);
        }

        console.log(inputs);

        return (
            <div className={ this.getClassNames() }>
                {inputs.map(function (result) {
                     return <InputRow key={result} />;
                })}
                <div className="row">
                    <button onClick={this.addRow} className="btn btn-success">Add more</button>    
                </div>
            </div>
        );
    }
});
like image 855
matiit Avatar asked Aug 15 '26 18:08

matiit


1 Answers

this.render() doesn't do anything. If you look at the function, it simply does some calculations and returns some data (the virtual dom nodes).

You should be using setState instead of directly modifying it. This is cleaner, and allows react to know something's changed.

addRow: function () {
    this.setState({rowCount: this.state.rowCount + 1});
},
like image 88
Brigand Avatar answered Aug 17 '26 12:08

Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!