Search code examples
javascriptreactjs-flux

How to trigger re-render on model change in ReactJS?


I am creating a react component using

React.render(<ReactComponent data="myData">, document.body);

Once the data model changes, I call render again using

React.render(<ReactComponent data="myData">, document.body);

Is this the right/recommended way to update my HTML?
Will this utilize the advantages of the React virtual DOM (i.e. rendering only the elements that have actually changed).

Also, should I be using state or properties when passing in myData?


Solution

  • You should be rendering only one main App component which does AJAX requests etc and uses the data model inside its render function to update sub components.

    When creating React components you should always keep the use of state minimal and move it up to the top level component, Instead you should use props to render child components.

    This article helped me a lot when i was first getting started with React: https://github.com/uberVU/react-guide/blob/master/props-vs-state.md

    so something like:

    var App = React.createClass({
        render: function(){
            return (
                <div>
                    <input type="button" onClick={this.handleClick}/>
                    <Dropdown items={this.state.countries}/>
                </div>
            )
        },
        getInitialState: function(){
            return {countries: {}};
        },
        componentDidMount: function(){
            var self = this;
            $.getJSON("countries", function(err, countries){
                self.setState({countries: countries});
            });
        },
        handleClick: function(){
            // every time the user does something, 
            // all you need to do is to update the state of the App 
            // which is passed as props to sub components
        }
    })
    
    React.render(React.createElement(App, {}), document.body);