Build a Simple ToDo App using React JS Functional Components and Hooks

react js todo app

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([]);
Now we have initiated the callback function to handle the submit action. When the user clicks on the submit button, the following function will invoke
const handleSubmit = (e) => {

setList((oldData) => [...oldData, data]);

setData("");

e.preventDefault();

};
Now, the below arrow function takes a callback to perform the removal of the listed task. It takes an argument id.
consthandleDelete=(id)=>{

console.log(id);

setList(oldData=>oldData.filter((elem,index)=>index!==id));

};
Here we are done with the functional part of the app. Below is the JSX content where we have added the form. onChange method is used to capture the live input in from the input box and set it to the state using the useState hook.
return (
<divclassName=”App”>
<form onSubmit={(e) => handleSubmit(e)}>
<label>
Enter Task:
<input
type=”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.

Leave a Comment