React JS is one of the most popular frontend frameworks. Learning React JS will help you to get a good job or increase your skillset further. In this post, we are going to build a simple ToDo app in React JS where you can add tasks and delete them.
We will be using React functional components and react hooks instead of class components. Making the ToDo app in react will help you to understand the concept of build-in state management and the importance of hooks.
So now without making any delay let’s dive into your favorite code manager-
Build a ToDo App using React JS
Below you can see the code where we imported some dependencies to run our react app. You can follow this process with me. All code will be in the App.js file. We are not making this app complicated by using props. We will keep it simple.
App.js
We have imported react dependencies and initiates the useState hooks for state management
import { useState } from "react";import { useState } from "react"; const [data, setData] = useState(""); const [list, setList] = useState([]);
const handleSubmit = (e) => { setList((oldData) => [...oldData, data]); setData(""); e.preventDefault(); };
consthandleDelete=(id)=>{ console.log(id); setList(oldData=>oldData.filter((elem,index)=>index!==id)); };
return (<divclassName=”App”><form onSubmit={(e) => handleSubmit(e)}><label>Enter Task:<inputtype=”text”value={data}onChange={(e) =>setData(e.target.value)}/><input type=”submit” value=”Submit” /></label></form><br /><div>{list.map((item, id) => (<divkey={id}><b>{item} </b><button onClick={() => handleDelete(id)}>X</button></div>))}</div></div>);}
Now we are done with the coding part. Just run the node server using “npm start” to check whether our ToDo app works or not. This is a very basic ToDo app to understand the basic concepts of form handling in the react JS.
If you have any queries regarding this app then feel free to ask in the comment section. Also, suggest us the next article about react js.
Below is the whole code of the ToDo app in react js with the output.