If render functions should be pure, how the view can get changed based on state?

1k views Asked by At

I am new to react and while going through the tutorials I found this ,

I am little confused with this. If render function should return same result each time how can I modify the display based on states ?

For example I have text with edit button. When I click on edit, text-box should appear with content of text and edit button changes to save.

1

There are 1 answers

0
Anand G On

"The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser." - https://facebook.github.io/react/docs/react-component.html#reference

is absolutely a correct statement in react. Changing a state cannot be done can't inside a render method. You can access the state inside the render but change. To change the state we use setState function in callback method which set the new state and ready to change anywhere in your component.

Note: setState expects the state to be initialized first. getInitialState is the function for the same and given in example below

eg.

var firstName = 'Anand';
var testExample = React.createClass({
    getDefaultProps: function () {
        return {
            name: 'React',
            message: 'This is the default message!'
        };
    },
    getInitialState: function () {
        return {
            name: this.props.name
        };
    },
    handleNewName: function (name) {
        this.setState({
            name: name
        });
    },
    render: function () {
        var name = this.state.name;
        var message = this.props.message;

        return (
            <div>
                <h1>{message}</h1>
                <h2>{name}</h2>
            </div>
        );
    }
});

Inside the handleNewName function we have changed the state which then used inside render. Hope this helps