Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying state list in JSX

I have some simple code:

class App extends React.Component {
  state = {
    letters: ["a", "b", "c"]
  };

  addLetter = () => {
    const { letters } = this.state;
    letters.push("d");
    this.setState({ letters });
  };

  render() {
    return (
      <div>
        <button onClick={this.addLetter}>Click to add a letter</button>
        <h1>letters: {this.state.letters}</h1>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Working example here.

When I click the button, the letter 'd' should be added to the letters in state. This works as intended. However, the letters do not update on the page as one would expect when state changes.

It's worth noting that:

<h1>letters: {this.state.letters.reduce((a, l) => a + l, "")}</h1>

or:

<h1>letters: {this.state.letters.toString()}</h1>

do update the page as expected.

Why is this?

like image 278
Colin Ricardo Avatar asked Nov 30 '25 15:11

Colin Ricardo


1 Answers

You need to replace the letter's state (the array), instead of mutating it (working example). According to the react docs: Do Not Modify State Directly.

When you're converting the array to a string, the current string is different from the previous string because strings are immutable. The array however stays the same array even if you add another item to it.

Example:

const a = [1, 2, 3];
const strA = a.toString();
a.push(4);
const strB = a.toString();

console.log(a === a); // true
console.log(strA === strB); // false

Solution: create a new array from the old one.

addLetter = () => {
  const { letters } = this.state;
  this.setState({ letters: [...letters, 'd'] });
}; 
like image 60
Ori Drori Avatar answered Dec 02 '25 05:12

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!