Vishnu Shekhawat Vishnu Shekhawat - 3 months ago 7
React JSX Question

Child prop value not updated on Window , but i can see it get updated in console

I dont know what i am doing wrong in this code, the prop value 'number' is not updating on front end , although in the console logs it value does get increament.

import React from 'react';
import { render } from 'react-dom';


class Parent extends React.Component{
constructor(props){
super(props);
this.number=0;
this.changeValue=this.changeValue.bind(this);
}

changeValue(){
console.log('-------------this.number',this.number);
this.number=this.number+1;
}

render(){
return(
<div>
<Child callMe={this.changeValue} increaseNo={this.number}></Child>
</div>
)
}
}


class Child extends React.Component{

render(){
return(
<div>
<button onClick={this.props.callMe}>CLick Me</button>
<h1>{this.props.increaseNo}</h1>
</div>
)
}
}

render(<Parent/> , document.getElementById('root'));

QoP QoP
Answer

You have to store this.number inside the component state, the component will only be re-rendered if its state changes or it receives new props.

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
           number: 0
        }
        this.changeValue=this.changeValue.bind(this);
    }

    changeValue(){
        this.setState({number: this.state.number + 1});
    }

    render(){
        return(
            <div>
                <Child callMe={this.changeValue} increaseNo={this.state.number}></Child>
            </div>
        )
    }
}


class Child extends React.Component{

    render(){
        return(
            <div>
                <button onClick={this.props.callMe}>CLick Me</button>
                <h1>{this.props.increaseNo}</h1>
            </div>
        )
    }
}

jsfiddle