1
export default class setState extends React.Component{
    constructor(){
        super();

        this.state = {
            data:[],`enter code here`
            'header':'this is header'
        }
    }

    updateState(){
        var arr = this.state.data;
        var temp = 'setState... ';
        arr.push(temp);

        this.setState({data:arr});
    }

    render(){
        return(
            <div>
                <h1>Set State</h1>
                <button onClick={this.updateState.bind(this)} >Update State </button>
                <p>{this.state.data}</p>
                <h3>{this.state.header}</h3>
                <h2>Random value : {Math.random()}</h2>
            </div>
        )
    }
}

I don't want to update h2 tag the "Random Value". When i click on the "Update button" i am pushing value in the array and doing "setState". But it also update my h2 tag.

1 Answer 1

1

Putting Math.random function in your render function will cause the value been changed on each render, instead, you can initialise your random value in constructor.

export default class setState extends React.Component{
    constructor(){
        super();

        this.state = {
            data:[],
            'header':'this is header'
        }
        //init random value here
        this.randomValue = Math.random();
    }

    updateState(){
        var arr = this.state.data;
        var temp = 'setState... ';
        arr.push(temp);

        this.setState({data:arr});
    }

    render(){
        return(
            <div>
                <h1>Set State</h1>
                <button onClick={this.updateState.bind(this)} >Update State </button>
                <p>{this.state.data}</p>
                <h3>{this.state.header}</h3>
                <h2>Random value : {this.randomValue}</h2>
            </div>
        )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.