Building a simple TODO List using React
Created using Microsoft Designer

Building a simple TODO List using React

In today's fast-paced web development world, mastering the ability to create dynamic, interactive user interfaces is essential for any frontend developer. One of the most popular libraries for building such interfaces is React—a powerful JavaScript library developed by Facebook, designed to make the creation of reusable UI components straightforward and efficient.

In this article, we’ll walk through the process of building a simple, yet fully functional TODO list application using React. While the project itself might seem basic, it incorporates several key React concepts that are foundational to larger, more complex applications.

Throughout this guide, you will not only learn how to build a TODO list but also explore key topics like:

  • Fetching data from a REST API (using JSONPlaceholder as our mock API).
  • Implementing client-side pagination to handle large datasets (can be enhanced).
  • Creating a smooth user experience with a loading spinner.
  • Styling the UI to provide a clean and user-friendly design.

Whether you’re a beginner trying to get hands-on experience with React or an experienced developer looking to refresh some core concepts, this guide will provide you with practical insights into how React can be used to efficiently manage data and build interactive user interfaces.

By the end of this article, you’ll not only have a working TODO list application but also an understanding of how React helps you create scalable and maintainable code for real-world projects.

Let’s get our hands dirty ?? and get started with building your first React TODO list!

Chapter 1: Introduction to Client-Side Pagination

When building web applications that display large sets of data, it's essential to provide a smooth and user-friendly experience by dividing the content into manageable pieces, known as pagination.

In this article, we'll explore how to implement client-side pagination using React and mock API data from JSONPlaceholder - Free Fake REST API (typicode.com), following these steps:

  1. Fetch TODO list items from a mock API.
  2. Implement pagination to display 10 items per page.
  3. Add a loading spinner for improved user experience.
  4. Provide navigation controls for easy page switching.
  5. Style pagination controls with simple CSS.

By the end of this guide, you’ll have a fully working paginated TODO list built with React.

Chapter 2: Setting Up Your Environment

Before we get into the code, ensure that you have the following prerequisites:

  • React: Make sure you have a React environment set up (or use JSFiddle). If you don’t, create one with create-react-app by running the following command:

npx create-react-app react-todo-pagination        

Once you have your environment set up, you’re ready to start building.

Chapter 3: Mock API for TODO Items

For this demonstration, we will use JSONPlaceholder, a free API for testing and prototyping.

The endpoint we will use is:

https://jsonplaceholder.typicode.com/todos        

This API returns a list of todo items with the following structure:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  }
  // ...more todos
]        

We'll fetch this data and display it in a paginated list.

The key properties we’ll use are:

  • title: The task description.
  • completed: A boolean that indicates whether the task is done or not.

Chapter 4: Fetching Data and Setting Up State

Our React component will use fetch to retrieve data from the API; initially, the data will be stored in the component state.

We'll also introduce basic pagination, splitting the TODO list into chunks of 10 items.

State Variables

  • allItems: Holds all fetched TODO items.
  • currentPage: Tracks the current page number.
  • itemsPerPage: Defines how many items are displayed per page (10 in this case).
  • isLoading: Controls whether the loading spinner is shown while the API call is in progress.

Fetching the Data

The componentDidMount lifecycle method is used to fetch data when the component first mounts; once the data is retrieved, we store it in the allItems state.

Chapter 5: Implementing Pagination Logic

To paginate the data, we calculate the indexOfFirstItem and indexOfLastItem based on the current page and the number of items per page:

const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = allItems.slice(indexOfFirstItem, indexOfLastItem);        

This code extracts a subset of items to display on the current page, and React's setState will trigger a re-render when the user navigates between pages.

We also calculate the total number of pages like so:

const totalPages = Math.ceil(allItems.length / itemsPerPage);        

The total number of pages determines how many pagination buttons we’ll display for navigation.

Chapter 6: Pagination Controls

Next, we add pagination buttons to navigate through the pages; these buttons will allow users to switch between pages.

Here’s how we generate the buttons:

<div className="pagination">
  {Array.from({ length: totalPages }, (_, index) => (
    <button
      key={index + 1}
      onClick={() => this.handlePageChange(index + 1)}
      className={currentPage === index + 1 ? 'active' : ''}
    >
      {index + 1}
    </button>
  ))}
</div>        

The handlePageChange method updates the current page when a user clicks a button, and the component then re-renders, showing the correct items for the selected page.

Chapter 7: Styling Pagination Controls with CSS

Now let’s style the pagination controls; here's a simple CSS snippet for styling the buttons:

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 10px 15px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  cursor: pointer;
}

.pagination button:hover {
  background-color: #ddd;
}

.pagination button.active {
  background-color: #3498db;
  color: white;
  border: 1px solid #3498db;
}        

This CSS ensures the pagination buttons are displayed horizontally and are easy to click.

The .active class highlights the current page.

Chapter 8: Enhancing the User Experience with a Spinner

To enhance the user experience, let’s add a loading spinner that appears while the data is being fetched; this keeps the user informed during the loading process.

We’ll modify the component to show a spinner while isLoading is true:

<div className="spinner"></div>        

Here’s the CSS for the spinner:

.spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #3498db;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  animation: spin 2s linear infinite;
  margin: 20px auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}        

Chapter 9: Full Code

HTML

CSS

TypeScript (React)

Chapter 10: Conclusion

By the end of this tutorial, you should have a fully functional React TODO list with client-side pagination and a loading spinner for better user experience; with simple styling for the pagination controls, you can easily navigate through large sets of data.

Here’s a recap of the main points covered:

  • Fetching TODO items from a real API (JSONPlaceholder).
  • Implementing client-side pagination in slices of 10 items.
  • Adding pagination buttons to navigate between pages.
  • Styling pagination and adding a loading spinner for a polished UX.

You can expand on this by implementing server-side pagination if your API supports it or customizing the pagination controls further.


Thanks for reading! If you found this useful, feel free to connect with me on LinkedIn for more insights on web development and frontend technologies.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了