React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a to-do list app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app todo-list
with NPM to create our React project.
We need the uuid
to let us create unique IDs for our to-do items easily.
To add it, we run:
npm i uuidv4
Create the To-Do App
To create the to-do list app, we write:
import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
export default function App() {
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const submit = (e) => {
e.preventDefault();
setTodos((todos) => [
...todos,
{
id: uuidv4(),
todo
}
]);
};
const deleteTodo = (index) => {
setTodos((todos) => todos.filter((_, i) => i !== index));
};
return (
<div className="App">
<form onSubmit={submit}>
<input value={todo} onChange={(e) => setTodo(e.target.value)} />
<button type="submit">Add</button>
</form>
{todos.map((t, i) => {
return (
<div key={t.id}>
{t.todo}
<button onClick={() => deleteTodo(i)}>delete</button>
</div>
);
})}
</div>
);
}
We have the todo
state which is bound to the input box.
The todos
state has an array of to-do items.
The submit
method is where we add the to-do items to the todos
array.
We call e.preventDefault()
to stop server-side form submission.
Then we call setTodos
with a callback to get the todos
and return an array with the original todos
items.
After that, we append the new item to it.
It has an id
created from the uuidv4
function.
todo
has the to-do item text.
The deleteTodo
function is called when we click the delete button.
In it, we call the setTodos
method with a callback that takes the original todos
array.
Then we return an array without the entry with the given index
.
We filter that entry out with the filter
method.
Then in the return
statement, we have a form that has the input
element with the value
and onChange
props to get the input value and set it with the onChange
callback respectively.
onSubmit
has the submit
function as its value. submit
is called when we click the Add button.
Below that, we have todos.map
callback with a callback that returns a div with the t.todo
rendered and a button to delete the item when we click it.
The key
prop is set to t.id
which is the unique ID.
This helps React identify the rendered array items properly.
Conclusion
We can create a to-do list app easily with React and JavaScript.