DEV Community

Cover image for Create Todo in React JS with typescript?
om pharate
om pharate

Posted on

Create Todo in React JS with typescript?

Creating a to-do application in ReactJS is a great first step towards upskilling. However, incorporating TypeScript into your project will also be beneficial for improving your TypeScript skills.

This blog post will teach you how to create a basic to-do app using TypeScript. The app will include essential features such as:

  • ⚒️ Creating new tasks
  • Deleting tasks
  • ↕️ Updating tasks
  • Marking tasks as complete

Getting Started With Vite.

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode
npm install
Enter fullscreen mode Exit fullscreen mode
npm run dev
Enter fullscreen mode Exit fullscreen mode

Now the basic folder structure will look like this.

Do not worry in case you have any additional files.
I have set up the tailwind CSS if you don't know how to set up tailwind CSS in React JS click here.

Image description

Here are the components/modules we are going to develop:

  • Navbar
  • Form
  • Todo List

Create components/Navbar.tsx

  • create a basic navbar with a title and about. Image description

Attach the navbar in app.tsx

Image description

Create components/Form.tsx

  • Create this basic form having an input field and a button "Add".
  • and a use state for getting value from the input field.

Image description

** However there is a problem in this code. **

  • the problem with the typescript.
  • because we are using typescript we are supposed to tell the datatype or what type of value It will hold in future to state(task).
  • and our state is empty there it will be considered undefined only.
  • and below in the input field, we are assigning a string to the state in onChange.
  • but the task(state) value was supposed to be undefined.

Image description

fix:

  • the value it will hold must be a string.
  • which will come from the user input. Image description

Add onClick functionality

Image description

Image description

Import Form in App.jsx

Image description

Create a global state of tasks array

  • create an array of tasks.
  • A task interface consists of a single task.
  • pass the setTasks to the Form component.
    Image description

    • accept task the setTask in Form component.
    • the type of prop would be: React.Dispatch<React.SetStateAction<task[]>>
    • in the typescript which type of props you are going to receive is required to mention.
    • in this case, setTask is a State action.

Image description

  • and on the onSubmit function we have pushed the task value (local state) to tasks (global state array).

Form.tsx
Image description

Create components/Todos.tsx

  • which will accept global state tasks.
  • and retrieve over through it. Image description

Final app.jsx

Image description

Output

Image description

Top comments (0)