Languages
[Edit]
EN

React - array as state

3 points
Created by:
nickkk0
647

In this article, we would like to show you how to use array as a state in React and later render some elements based on the array. 

The most common problem when react beginners try to use arrays are:

  • missing unique key property for each array item,
  • how to modify array and refresh component state after modification.

In this article we would like to show 4 basics operations on arrays:

  1. elements rendering based on array items,
  2. items adding,
  3. items deleting,
  4. items modifying.

Check below section to see how it works.

Note: below solutions are summary of the most commonly used practices.

1. Elements rendering based on array items example

It is very important to add for each children key property - that helps React to detect DOM changes in an optimal way. To iterate over array we can use built-in JavaScript map() function.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [list, setList] = React.useState(['one', 'two', 'three']);
  return (
    <ul>
      {list.map(item => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

2. Items adding into array example

To notify React about state change we need to pass to state always different reference than the current one. That situation makes we can add item into array with [...list, newItem] operation that returns new object with the same items).

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [list, setList] = React.useState(['one', 'two', 'three']);
  const handleAddClick = () => {
     const number = list.length + 1;
      setList([...list, 'added-' + number]);
  };
  return (
    <div>
      <ul>
        {list.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <button onClick={handleAddClick}>Add item</button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Remember: by using list.push() method we will not see any component change because reference stored as state will be not changed - component is re-rendered only on reference or value change in state.

3. Items deleting from array example

One of the most simple way how to remove element from array and make copy of them is to use filter() method.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [list, setList] = React.useState(['one', 'two', 'three']);
  const handleRemoveClick = () => {
    setList(list.filter((item, index) => item !== 'two'));
  };
  return (
    <div>
      <ul>
        {list.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <button onClick={handleRemoveClick}>Remove 'two' item</button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

4. Items modifying in array example

Using map() method we are able to transform array into a new one. So this way we are able to change only desired items.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [list, setList] = React.useState(['one', 'two', 'three']);
  const handleRemoveClick = () => {
    setList(list.map((item, index) => item === 'two' ? 'new-two-value' : item));
  };
  return (
    <div>
      <ul>
        {list.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <button onClick={handleRemoveClick}>Remove 'two' item</button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

 

See also

  1. React - useArray() custom hook example 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - array as state
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join