0% found this document useful (0 votes)
13 views

Activity 7oct

Uploaded by

skip10146
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Activity 7oct

Uploaded by

skip10146
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

import React, { useReducer, useRef } from 'react';

import './App.css';

const initialState = {

tasks: [],

};

const ADD_TASK = 'ADD_TASK';

const REMOVE_TASK = 'REMOVE_TASK';

const TOGGLE_TASK = 'TOGGLE_TASK';

const reducer = (state, action) => {

switch (action.type) {

case ADD_TASK:

return {

...state,

tasks: [

...state.tasks,

id: Date.now(),

text: action.payload.text,

completed: false,

},

].sort((a, b) => a.text.localeCompare(b.text)),

};

case REMOVE_TASK:

return {

...state,

tasks: state.tasks.filter((task) => task.id !== action.payload.id),

};

case TOGGLE_TASK:
return {

...state,

tasks: state.tasks.map((task) =>

task.id === action.payload.id

? { ...task, completed: !task.completed }

: task

),

};

default:

return state;

};

const TodoApp = () => {

const [state, dispatch] = useReducer(reducer, initialState);

const inputRef = useRef();

const addTask = () => {

const text = inputRef.current.value;

if (text) {

dispatch({ type: ADD_TASK, payload: { text } });

inputRef.current.value = '';

};

const removeTask = (id) => {

dispatch({ type: REMOVE_TASK, payload: { id } });

};
const toggleTask = (id) => {

dispatch({ type: TOGGLE_TASK, payload: { id } });

};

return (

<div>

<h1>Todo App</h1>

<input ref={inputRef} type="text" placeholder="Add a new task..." />

<button onClick={addTask}>Add Task</button>

<ul>

{state.tasks.map((task) => (

<li key={task.id} style={{ textDecoration: task.completed ? 'line-through' : 'none' }}>

{task.text}

<button onClick={() => toggleTask(task.id)}>Toggle</button>

<button onClick={() => removeTask(task.id)}>Remove</button>

</li>

))}

</ul>

</div>

);

};

export default TodoApp;

You might also like