The Simplest React Todo List for your interview
the simplest to-do List app with (Next js).
Here I am not doing any CSS stuff or any extra work to just focus on the logical part, and to be a reference for me and hopefully for other people.
What we will do?
- A todo list app :
- Input field
- Button
- Show the lists in un-order list HTML(JSX to be specific )
You can do it in 2 ways :
You can mention this in the interview.
- one way using .bind() method .
- Another way using State in the functional component.
the functional component (That is what we will do today ).
Let's Go?
we will use :
- useRef: It can be used to store a mutable value that does not cause a re-render when updated.
- useState: track state in a function component.
import { useState } from "react";
import { useRef } from "react";
// LET'S GO .
const TodoList = () => {
// create a useState of Arrays.
const [todos, setTodos] = useState([]);
// Store useRef in var for easy use.
const inputRef = useRef();
//THE LOGICAL PART (When you click the button)
const handleSubmit = (e) => {
//preventDefault: Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
e.preventDefault();
const newTodo = inputRef.current.value;
//put the new value with the others.
setTodos([...todos, newTodo]);
inputRef.current.value = "";
};
return (
<div>
{/* Create the form */}
<div>
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
<button type='submit'>Add</button>
</form>
</div>
<ul>
{/* MAP IT Here */}
{todos.map((todo) => (
<li key={todo.id}>{todo}</li>
))}
</ul>
</div>
);
};
export default TodoList;
you can add more functionality as you like, you can put a delete button or an edit button or re-order the list.
we can cover all of that in other posts but for now congrats you are done.