Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Todo using useReducer in React
Touhidul Shawan
Touhidul Shawan

Posted on

     

Todo using useReducer in React

What is React?

React is ajavaScript library that use to build our user interface for applications.

What isuseReducer

useReducer is a react hook that is used to implement our complex state of applications.

In this simple todo app I have used react with typescript template

Step 1:

First of all, create a project called todo usingcreate-react-app
npx create-react-app todo --template typescript
After creating the projectcd to todo folder then run
npm start oryarn start

Step 2:

  1. Create two folder calledcontainers ,components
  2. Create a file calledTodos.tsx in containers
  3. Import Todos.tsx file in App.tsx and use it
import*asReactfrom"react";importTodosfrom"./container/Todos";constApp:React.FC=()=>{return<Todos/>;};exportdefaultApp;
Enter fullscreen modeExit fullscreen mode
  1. Create an interface that will represent the blueprint of a todo item in Todos.tsx file
exportinterfaceTodosProps{id:string;todoName:string;isComplete:boolean;}
Enter fullscreen modeExit fullscreen mode
  1. Create interfaces for various activities of the app like add todo item, remove todo item and toggle the todo to check that todo item is completed or not
interfaceAddTodoAction{type:"ADD_TODO";payload:{name:string};}interfaceModifyTodoAction{type:"TOGGLE_TODO"|"DELETE_TODO";payload:{id:string};}
Enter fullscreen modeExit fullscreen mode
  1. action type
exporttypeTodoAction=AddTodoAction|ModifyTodoAction
Enter fullscreen modeExit fullscreen mode
  1. Create a reducer function called todoReducer that is used with useReducer to control the state with action.
consttodoReducer=(todos:Array<TodosProps>,action:TodoAction)=>{switch(action.type){case"ADD_TODO":return[...todos,newTodo(action.payload.name)];case"TOGGLE_TODO":returntodos.map((todo)=>{if(todo.id===action.payload.id){return{...todo,isComplete:!todo.isComplete};}returntodo;});case"DELETE_TODO":returntodos.filter((todo)=>todo.id!==action.payload.id);default:returntodos;}};
Enter fullscreen modeExit fullscreen mode
  1. Create a new todo item structure with this function
constnewTodo=(todoName:string):TodosProps=>{return{id:uuidv4(),todoName:todoName,isComplete:false};};
Enter fullscreen modeExit fullscreen mode
  1. Todos.tsx
import*asReactfrom"react";import{useReducer}from"react";import{v4asuuidv4}from"uuid";importTodofrom"../components/Todo";importTodoInputfrom"../components/TodoInput";exportinterfaceTodosProps{id:string;todoName:string;isComplete:boolean;}interfaceAddTodoAction{type:"ADD_TODO";payload:{name:string};}interfaceModifyTodoAction{type:"TOGGLE_TODO"|"DELETE_TODO";payload:{id:string};}exporttypeTodoAction=AddTodoAction|ModifyTodoAction;consttodoReducer=(todos:Array<TodosProps>,action:TodoAction)=>{switch(action.type){case"ADD_TODO":return[...todos,newTodo(action.payload.name)];case"TOGGLE_TODO":returntodos.map((todo)=>{if(todo.id===action.payload.id){return{...todo,isComplete:!todo.isComplete};}returntodo;});case"DELETE_TODO":returntodos.filter((todo)=>todo.id!==action.payload.id);default:returntodos;}};constnewTodo=(todoName:string):TodosProps=>{return{id:uuidv4(),todoName:todoName,isComplete:false};};constTodos:React.FC=()=>{const[todos,dispatch]=useReducer(todoReducer,[]);constrenderTodos=todos.map((todo)=>(<Todokey={todo.id}id={todo.id}todoName={todo.todoName}isComplete={todo.isComplete}dispatch={dispatch}/>));console.log(todos);return(<div><TodoInputdispatch={dispatch}/>{renderTodos}</div>);};exportdefaultTodos;
Enter fullscreen modeExit fullscreen mode
  1. Create a file calledTodoInput.tsx in components folder

TodoInput.tsx

This component is responsible for rendering a form with an input field and a submit button

import*asReactfrom"react";import{useState}from"react";import{TodoAction}from"../container/Todos";interfaceTodoInputProps{dispatch:React.Dispatch<TodoAction>;}constTodoInput:React.FC<TodoInputProps>=({dispatch})=>{const[todoName,setTodoName]=useState("");consthandleChange=(evt:React.FormEvent<HTMLInputElement>)=>{setTodoName(evt.currentTarget.value);};consthandleSubmit=(evt:React.FormEvent)=>{evt.preventDefault();dispatch({type:"ADD_TODO",payload:{name:todoName}});setTodoName("");};return(<formonSubmit={handleSubmit}><inputtype="text"placeholder="Type your todo...."value={todoName}onChange={handleChange}/><buttontype="submit">AddTodo</button></form>);};exportdefaultTodoInput;
Enter fullscreen modeExit fullscreen mode
  1. Display all todo item in Todo.tsx file in components folder
import*asReactfrom"react";import{TodosProps,TodoAction}from"../container/Todos";exportinterfacePropsextendsTodosProps{dispatch:React.Dispatch<TodoAction>;}constTodo:React.FC<Props>=({dispatch,id,isComplete,todoName})=>{consthandleDelete=(id:string)=>{dispatch({type:"DELETE_TODO",payload:{id:id},});};consthandleToggle=(id:string)=>{dispatch({type:"TOGGLE_TODO",payload:{id:id},});};return(<div><div><pstyle={{textDecoration:`${isComplete?"line-through":""}`}}>{todoName}</p></div><div><buttononClick={()=>handleToggle(id)}>Toggle</button><buttononClick={()=>handleDelete(id)}>Delete</button></div></div>);};exportdefaultTodo;
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hello World!
  • Location
    404
  • Education
    M.Sc in Software Engineering
  • Joined

More fromTouhidul Shawan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp