I am building React Todo app. However, I can't understand how todos type became object? In the App.js, we set it an array. In the Form.js we set
setTodos([...todos, { text: inputText, id: Math.random() * 1000 }]);
I didn't understand what is going on in this line. Could you please help?
App.js
import React, { useState } from "react";
import "./App.css";
//Importing Components
import Form from "./components/Form";
import TodoList from "./components/TodoList";
function App() {
const [inputText, setInputText] = useState("");
const [todos, setTodos] = useState([]);
return (
<div className="App">
<header>
<h1>Hitay's Todo List</h1>
</header>
<Form
todos={todos}
setTodos={setTodos}
inputText={inputText}
setInputText={setInputText}
/>
<TodoList todos={todos} />
</div>
);
}
export default App;
Form.js
import React from "react";
const Form = ({ inputText, setInputText, todos, setTodos }) => {
//Here I can write JavaScript code and Function
const inputTextHandler = (e) => {
setInputText(e.target.value);
};
const submitTodoHandler = (e) => {
e.preventDefault();
setTodos([...todos, { text: inputText, id: Math.random() * 1000 }]);
setInputText("");
};
return (
<form>
<input
value={inputText}
onChange={inputTextHandler}
type="text"
className="todo-input"
/>
<button onClick={submitTodoHandler} className="todo-button" type="submit">
<i className="fas fa-plus-square"></i>
</button>
</form>
);
};
export default Form;
TodoList.js
import React from "react";
//Import Components
import Todo from "./Todo";
const TodoList = ({ todos }) => {
console.log(typeof todos); //object??
return (
<div className="todo-container">
<ul className="todo-list"></ul>
</div>
);
};
export default TodoList;
Todos is array of objects. But one single todo is an object. todos looks like this normally;
todos = [
{ text: "work", id: 12314 },
{ text: "eat", id: 12321414 },
{ text: "drink", id: 12311234 },
]
The line you showed there setTodos([...todos, { text: inputText, id: Math.random() * 1000 }]);
you are getting all the todos and spreading into new array with spread opearator ( ...todos
). Then you add your new todo inside of it.