Kalhan Dhar
Kalhan Dhar

Reputation: 1

React Conditional Update of a List

I am new to react and I am trying to understand how to change the elements of a list. Below is a simple example of what I am trying to do.

const numbers = [1, 2, 3, 4, 5];
/* 
if(numbers[1] == 2)
   numbers[1] = 5;
else 
   numbers[1] = 0;
*/
const listItems = numbers.map((number) =>
  <li>{number}</li>
);

I need to update an element of a list based on the comments above. But I am running into a lot of errors. Is this the wrong way to work with lists in React. Thanks.

Upvotes: 0

Views: 163

Answers (2)

hackape
hackape

Reputation: 19957

First, you need to understand your listItems is NOT a component, it's just an array of react elements. So you need to put them inside the render method of some component.

class ListItemComp extends React.Component {
  render () {
    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
      <li>{number}</li>
    );

    return (<ul>{listItems}</ul>);
  }
}

Second, if you want to make change to the data, and you want react to know that change and re-render the view, then you need to call this.setState() somewhere, and make sure the data changed is accessible from this.state. So let's change the component a bit.

class ListItemComp extends React.Component {
  constructor () {
    super()

    const numbers = [1, 2, 3, 4, 5];
    this.state = {
      numbers: numbers
    };

    // first it'll render "1,2,3,4,5"
    // wait 3 seconds, it re-render to "1,5,3,4,5"
    setTimeout(() => { 
      if (numbers[1] == 2)
        numbers[1] = 5;
      else 
        numbers[1] = 0;

      this.setState({ numbers: numbers });
    }, 3000);
  }

  render () {
    const listItems = this.state.numbers.map((number) =>
      <li>{number}</li>
    );

    return (<ul>{listItems}</ul>);
  }
}

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191986

Array#map callback receives the current index as the 2nd param, so you can use a nested ternary in JSX, and modify the rendered item if the index is 1:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number, index) =>
  <li>{index === 1 ? (number === 2 ? 5 : 0) : number}</li>
);

Upvotes: 1

Related Questions