DEV Community

Coding Jitsu
Coding Jitsu

Posted on

An Introduction to TypeScript: Building a Simple Todo App with React

TLDR: Checkout the video instead:

TypeScript is a statically typed superset of JavaScript that adds optional static typing to the language. When combined with React, a popular JavaScript library for building user interfaces, TypeScript provides a powerful development experience. In this article, we'll explore the basics of TypeScript with React and demonstrate how to create a simple todo app using this combination.

Setting Up the Development Environment

To get started with TypeScript and React, you'll need to set up your development environment. Here's a step-by-step guide:

  1. Install Node.js: Make sure you have Node.js installed on your machine. You can download the latest version from the official Node.js website.

  2. Create a New React Project: Open a command prompt or terminal and navigate to the directory where you want to create your project. Run the following command to create a new React project with TypeScript:

   npm create vite@latest ./
Enter fullscreen mode Exit fullscreen mode

Image of terminal showing vite installing react project

This command creates in the current directory called typescript-tutorail and sets up a new React project with TypeScript.

  1. Run the following command to install all the dependency:
   npm install
Enter fullscreen mode Exit fullscreen mode

Now you're ready to start building your todo app with TypeScript and React!

Creating a Simple Todo App

Now that your development environment is set up, let's create a simple todo app using TypeScript and React. We'll start by defining the structure of a todo item and implementing the basic functionalities.

  1. Create a components folder in the src/components/TodoApp.tsx project.

  2. Define the TodoItem Interface: Add the following code to the TodoApp.tsx file:

   interface TodoItem {
     id: string;
     text: string;
     completed: boolean;
   }
Enter fullscreen mode Exit fullscreen mode

This interface defines the structure of a todo item, including its id, text, and completed properties.

  1. Create the TodoApp Component with the following code:
   import { useState } from 'react';

   interface TodoItem {
        id: string;
        text: string;
        completed: boolean;
      }

   const TodoApp = () => {
     const [todos, setTodos] = useState<TodoItem[]>([]);
     const [newTodo, setNewTodo] = useState('');

     const addTodo = () => {
       if (newTodo !== '') {
         const newId = crypto.randomUUID();
         const newTodoItem: TodoItem = {
           id: newId,
           text: newTodo,
           completed: false,
         };
         setTodos([...todos, newTodoItem]);
         setNewTodo('');
       }
     };

     const removeTodo = (id: string) => {
       const updatedTodos = todos.filter((todo) => todo.id !== id);
       setTodos(updatedTodos);
     };

     const toggleComplete = (id: string) => {
       const updatedTodos = todos.map((todo) => {
         if (todo.id === id) {
           return { ...todo, completed: !todo.completed };
         }
         return todo;
       });
       setTodos(updatedTodos);
     };

     return (
       <div>
         <h1>Todo App</h1>
         <input
           type="text"
           value={newTodo}
           onChange={(e) => setNewTodo(e.target.value)}
         />
         <button onClick={addTodo}>Add Todo</button>
         <ul>
           {todos.map((todo) => (
             <li key={todo.id}>
               <input
                 type="checkbox"
                 checked={todo.completed}
                 onChange={() => toggleComplete(todo.id)}
               />
               <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
                 {todo.text}
               </span>
               <button onClick={() => removeTodo(todo.id)}>Remove</button>
             </li>
           ))}
         </ul>
       </div>
     );
   };

   export default TodoApp;
Enter fullscreen mode Exit fullscreen mode

This code defines the TodoApp component, which represents the todo app. It uses the useState hook to manage the list of todos and the new todo input field. It provides functions to add a todo, remove a todo, and toggle the completion status of a todo.

  1. Update the src/App.tsx file to render the TodoApp component: Replace the default App component in the App.tsx file with the following code:
   import TodoApp from './TodoApp';

   function App() {
     return (
       <div className="App">
         <TodoApp />
       </div>
     );
   }

   export default App;
Enter fullscreen mode Exit fullscreen mode

This code imports the TodoApp component and renders it within the App component.

  1. Start the Development Server: Open the command prompt or terminal and make sure you're in the project directory. Run the following command to start the development server:
   npm run dev
Enter fullscreen mode Exit fullscreen mode

This command starts the development server and opens the app in your default browser.

You should now see the todo app running in your browser. You can add new todos, mark them as completed by checking the checkboxes, and remove them by clicking the "Remove" buttons.

Conclusion

In this article, we introduced TypeScript with React and demonstrated how to create a simple todo app using this combination. TypeScript's static typing and React's component-based architecture provide a robust and maintainable way to build user interfaces. By leveraging the power of TypeScript and React together, you can create more reliable and scalable applications. So, start exploring TypeScript and React, and unlock their potential for your projects. Happy coding!
Other Articles to check out:
TypeScript Cheat Sheet
findLast() and findLastIndex()

Top comments (0)