Search code examples
.netreactjsserver-side

React js - updating a list of items after initial render


I am very new to react (angular background) and am trying to render a list of items that will be updated with new items on click of a button. Regarding the following code below, the initial list is displayed (2 records), however, after onClick i can see the console.log message but the rendered items do not change. Is something wrong with this implementation?

Note: I am using server side rendering with .net.

var Foo = React.createClass({
items: [
    '<h1>Initial Item 1</h1>', 
    '<h1>Initial Item 2</h1>'
],
getItems: function () {
    return this.items;
},
getMoreItems: function() {
    console.log('Retrieving more items..');

    // To eventually be replaced with async call for more data
    this.items.push('<h1>Additional Item 1</h1>');
    this.items.push('<h1>Additional Item 2</h1>');
    this.items.push('<h1>Additional Item 3</h1>');
},
render: function() {
    return (
        <div>
            {
                this.getItems().map(function(item) {
                    return (
                        <div dangerouslySetInnerHTML={{__html: item}} />
                    );
                })
            }

            <button className="more btn btn-info" onClick={this.getMoreItems}>
                Get more items...
            </button>
        </div>
    );
}
});

Solution

  • You need to use your component's State.

    React components will automatically re-render whenever their state or props change. this.setState({items: items}) in your getMoreItems method, matched with this.state.items in your getItems method should solve the problem.

    Be sure not to change the state directly though. If you want to push new items into the state, interact with a separate array and then set that with the same this.setState statement. I.e., do not do: this.state.items.push().