React ES6 Array Methods

ES6 introduced several new array methods that can be used with React to manipulate arrays in a more concise and functional way. Here are some examples of using array methods in a React component:

				
					import React, { useState } from 'react';

const MyComponent = () => {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Buy milk', completed: false },
    { id: 2, text: 'Do laundry', completed: false },
    { id: 3, text: 'Call mom', completed: true },
  ]);

  const handleToggle = (id) => {
    setTodos((prevTodos) =>
      prevTodos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const handleDelete = (id) => {
    setTodos((prevTodos) => prevTodos.filter((todo) => todo.id !== id));
  };

  const incompleteTodos = todos.filter((todo) => !todo.completed);
  const sortedTodos = todos.sort((a, b) => b.completed - a.completed);

  return (
    <div>
      <h1>Todo List</h1>
      {incompleteTodos.length ? (
        <p>You have {incompleteTodos.length} incomplete tasks.</p>
      ) : (
        <p>All tasks completed!</p>
      )}
      <ul>
        {sortedTodos.map((todo) => (
          <li
            key={todo.id}
            style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
          >
            {todo.text}
            <button onClick={() => handleToggle(todo.id)}>Toggle</button>
            <button onClick={() => handleDelete(todo.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default MyComponent; 

				
			

In this example, we use the filter method to create a new array called incompleteTodos that contains only the incomplete tasks. We also use the sort method to create a new array called sortedTodos that sorts the tasks by completed status.

We use the map method in the handleToggle function to create a new array with the updated completed status for the clicked task. We use the spread operator () to create a new object with the same properties as the original object, except for the completed property, which is toggled.

Finally, we use the filter method in the handleDelete function to create a new array without the clicked task.

Using array methods with React can make your code more functional and readable, especially for manipulating arrays with complex logic.

Join To Get Our Newsletter
Spread the love