user10398929
user10398929

Reputation:

Child component not updating on state change

I am trying to pass a value to child component yet the value doesn't not update as the parent component value changes. Here is my work

Child component:

class Test extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: this.props.data,
    }
  }

  render() {
    return(
      <div>{this.state.data}</div>
    )
  }
}


export default Test;

Parent js file

constructor(props) {
  super(props)
  this.state = {
    val: 0,
  }
  this.addVal = this.addVal.bind(this)
}

addVal() {
  let val = this.state.val
  val = val + 1
  console.log(val)
  this.setState({
    val
  })
}
render() {
  return(
    <div>
      <Button onClick={this.addVal}> add </Button>
      <Test data={this.state.val} />
    </div>
  )
}

The value gets updated on the parent component however, the child component does not get the updated value. What am I missing?

Upvotes: 1

Views: 320

Answers (2)

paddycorr
paddycorr

Reputation: 111

state is unnecessary in the child component. It should be enough to render this.props.data since that is what you are passing to the child from the parent.

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36574

The constructor() only runs once in the start. When the parent is updated it sends new props to the Test but it doesnot change state.data to props.data after the component is rendered first time

You are printing this.state variable which is not updated. Instead you should print value from this.props

render(){
    return(
      <div>{this.props.data}</div>
      )
}

If you want to detect the new props you can use compnentWillRecieveProps()

componentWillRecieveProps(nextProps){
    this.setState({data:nextProps.data})
}

Upvotes: 2

Related Questions