I am currently working on a react.js to do list. The code below is what i've done so far which are relevant to the question
Main File (App.js)
import './App.css';
import Navbar from './components/Header'
import Container from './components/Container.js';
import Input from './components/Input';
import { useState } from 'react';
function App() {
let todo =[
{id:Math.random()*10000,
title: "Walk the dog",
completed:false},
{id:Math.random()*10000,
title: "Wash Dishes",
completed:false},
]
const [list,setList] = useState(todo)
function addTodo(e) {
let value = e.target.previousElementSibling.value;
let newtodo = [...todo,{id: Math.random()*10000, title: value, completed:false}]
setList(newtodo)
console.log(todo)
}
return (
<div className="body">
<Navbar className="Navbar"/>
<Input method = {addTodo} />
<Container list={newtodo}/>
</div>
);
}
export default App;
Container Component
const Container =({list , method})=> {
return(
<div className="container">
{list.map(element => {
return(
<TodoComponent className="todo-list" data={element}/>
)
})}
</div>
)
}
export default Container
Todo List Component
import React from "react";
const TodoComponent = ({data})=> {
return(
<div className="todo-list" >
<h3 key={data.id} >{data.title}</h3>
<i className="fas fa-trash"></i>
</div>
)
}
export default TodoComponent
Form Input
import React from "react"
const Input = ({method}) => {
return (
<div className="form">
<input placeholder="add task.."></input>
<button onClick= {method}>
Add
</button>
</div>
)
}
export default Input
The problem is, whenever I click the button next to the input field, the "todo" array updates, but the updates do not get rendered in the to do list. How do i fix this? Thanks in advance. If this was too confusing, please let me know.
Your addTodo function is incorrect. instead ..todo it should be ...list. try this
function addTodo(e) {
let value = e.target.previousElementSibling.value;
let newtodo = [...list,{id: Math.random()*10000, title: value, completed:false}]
setList(newtodo)
console.log(todo)
}
and you are not passing list state to <Container/> component
insted of
<Container list={newtodo}/>
it should be
<Container list={list}/>
First verify if you have the desired value in your addTodo function. The problem is you are updating the todo array which doesn't change because it is not a state variable. Try:
function addTodo(e) {
let value = e.target.previousElementSibling.value;
setList(list => [...list, {id: Math.random()*10000, title: value, completed:false})
}