Todo List Web App With React And Vite – PART 4: Components Building
In the previous parts of this series, we have set up the project, created the necessary files and folders, and added the basic functionality for our todo list web app using React and Vite. Now in this part, we will focus on building the components that will make up our app.
Creating the TodoItem Component
The first component we will create is the TodoItem component. This component will represent each individual todo item in our list. We will define this component in a new file called TodoItem.js inside the components folder.
<!-- TodoItem.js -->
import React from 'react';
const TodoItem = ({ todo, toggleTodo }) => {
return (
<div>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
/>
<p style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>{todo.text}</p>
</div>
);
};
export default TodoItem;
In this TodoItem component, we are using a functional component and destructuring the props to access the todo object and the toggleTodo function. We are then rendering a checkbox input and a paragraph element to display the todo text. We also apply a line-through style to the paragraph text if the todo is completed.
Creating the TodoList Component
Next, we will create the TodoList component, which will represent the entire list of todos. This component will also be defined in a new file called TodoList.js inside the components folder.
<!-- TodoList.js -->
import React from 'react';
import TodoItem from './TodoItem';
const TodoList = ({ todos, toggleTodo }) => {
return (
<div>
<h2>Todo List</h2>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
toggleTodo={toggleTodo}
/>
))}
</div>
);
};
export default TodoList;
In this TodoList component, we are using a functional component and destructuring the props to access the todos array and the toggleTodo function. We are then rendering a heading element and mapping over the todos array to render a TodoItem component for each todo in the list.
Now that we have created the TodoItem and TodoList components, we can use them in our App component to render the todo list. We will import the TodoList component and pass the todos and toggleTodo function as props to it.
With these components in place, we now have a fully functional todo list web app that we have built from scratch using React and Vite. In the next part of this series, we will look at adding styling to our app to make it look more visually appealing.