Skip to content
Advertisement

React – changing state not updating elements rendered from variable

So, I have stored a component in a variable const span = <span>{this.state.text}</span>. Now when I render this element and update the text within the state. The element is not re-rendered.

So this is my code

class App extends React.Component {
  state = {
    text: 'hey'
  }
  span = <span>{this.state.text}</span>

  render() {
    return (
      <div>
        {this.span}
        <div>State: {this.state.text}</div>
        <button onClick={()=>{this.setState({text: 'hello'})}}>Update</button>
      </div>
    )
  }
}

So even after updating the state, the span has the initial value of the state. Is there any way to make this dynamic? I’m a newbie here.

Advertisement

Answer

As per your code span is an instance property of App that once set will remain the same through out the lifecycle of your component unless set again manually. You would have to include that span html creation inside the render like so :-

class App extends React.Component {
  state = {
    text: 'hey'
  }
  render() {
    return (
      <div>
         <span>{this.state.text}</span>
        <div>State: {this.state.text}</div>
        <button onClick={()=>{this.setState({text: 'hello'})}}>Update</button>
      </div>
    )
  }
}

This is valid as well :-

class App extends React.Component {
  state = {
    text: 'hey'
  }
  span = <span>{this.state.text}</span>
  render() {
    this.span = <span>{this.state.text}</span>
    return (
      <div>
        {this.span}
        <div>State: {this.state.text}</div>
        <button onClick={()=>{this.setState({text: 'hello'})}}>Update</button>
      </div>
    )
  }
}

The below with having another function like renderSpan is valid as well :-

class App extends React.Component {
  state = {
    text: 'hey'
  }
  renderSpan = function(){
    return <span>{this.state.text}</span>
  }
  render() {
    return (
      <div>
        {this.renderSpan()}
        <div>State: {this.state.text}</div>
        <button onClick={()=>{this.setState({text: 'hello'})}}>Update</button>
      </div>
    )
  }
}

The below is achieved using the shouldComponentUpdate lifecycle method :-

class App extends React.Component {
  state = {
    text: 'hey'
  }
  span = <span>{this.state.text}</span>

  shouldComponentUpdate(nextProps,nextState){
     this.span = <span>{nextState.text}</span>
     return true;
  }

  render() {
    return (
      <div>
        {this.span}
        <div>State: {this.state.text}</div>
        <button onClick={()=>this.setState({text:'hello'})}>Update</button>
      </div>
    )
  }
}

There are just too many ways. It’s good to know why all of them work. Knowing their working means to understand both JavaScript (Here specifically ES6 Class) and React (Here specifically Class Components).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement