How to use array methods in real project (example) add new record

How to use array methods in real project (example) add new record

Sure, let’s consider a simple React project where we have an array of items representing tasks, and we want to perform various operations on this array using different array methods.

Assume we have a project management application where users can add, delete, and mark tasks as completed. Here’s how we can utilize array methods in such a project:

import React, { useState } from react;

function App() {
const [tasks, setTasks] = useState([
{ id: 1, title: Task 1, completed: false },
{ id: 2, title: Task 2, completed: true },
{ id: 3, title: Task 3, completed: false },
]);

// Add a new task
const addTask = () => {
const newTask = {
id: tasks.length + 1,
title: `Task ${tasks.length + 1}`,
completed: false,
};
setTasks([…tasks, newTask]);
};

// Delete a task
const deleteTask = (id) => {
setTasks(tasks.filter(task => task.id !== id));
};

// Toggle completion status of a task
const toggleCompletion = (id) => {
setTasks(tasks.map(task => {
if (task.id === id) {
return { task, completed: !task.completed };
}
return task;
}));
};

return (
<div>
<h1>Task Manager</h1>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map(task => (
<li key={task.id}>
<input
type=checkbox
checked={task.completed}
onChange={() => toggleCompletion(task.id)}
/>
<span style={{ textDecoration: task.completed ? line-through : none }}>
{task.title}
</span>
<button onClick={() => deleteTask(task.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

export default App;

In this example:

We use the useState hook to manage the array of tasks.
addTask function adds a new task to the array.
deleteTask function removes a task from the array.
toggleCompletion function toggles the completion status of a task.
We render the tasks in a list, allowing users to mark them as completed or delete them.

This example demonstrates how you can use array methods like map(), filter(), and map() in a React project to manage and manipulate arrays of data effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *