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 (
Todo List
{incompleteTodos.length ? (
You have {incompleteTodos.length} incomplete tasks.
) : (
All tasks completed!
)}
{sortedTodos.map((todo) => (
-
{todo.text}
))}
);
};
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.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.