how i can add more arrays in use state when i add a array by using a setAddtaskv array will be add but format is not true
import react,{useState,useEffect} from 'react'
const App = () => {
const [addtaskV,setAddtaskv] = useState([
{ id: 1, title: "Alabama",text:"Test" },
{ id: 2, title: "Georgia",text:"Test" },
{ id: 3, title: "Tennessee",text:"Test" }
]);
const addTask = () =>
{
const title = document.getElementById('title').value;
const text = document.getElementById('text').value;
}
return (
<div>
<input type="text" placeholder="Title" id="title"/>
<input type="text" placeholder="Write some text" id="text" />
<button onClick={addTask}>Add</button>
</div>
);`enter code here`
}
export default App;
CodePudding user response:
On your addTask
you could do this
const addTask = () => {
const title = document.getElementById("title").value;
const text = document.getElementById("text").value;
setAddtaskv((previousState) => [
...previousState,
{ id: addtaskV.length 1, title: title, text: text }
]);
};
The spread
on ...previousState
means that you get whatever is already inside there and you add your new object to it.
Here's the full component
import react, { useState, useEffect } from "react";
const App = () => {
const [addtaskV, setAddtaskv] = useState([
{ id: 1, title: "Alabama", text: "Test" },
{ id: 2, title: "Georgia", text: "Test" },
{ id: 3, title: "Tennessee", text: "Test" }
]);
const addTask = () => {
const title = document.getElementById("title").value;
const text = document.getElementById("text").value;
setAddtaskv((previousState) => [
...previousState,
{ id: addtaskV.length 1, title: title, text: text }
]);
};
return (
<>
<div>
<input type="text" placeholder="Title" id="title" />
<input type="text" placeholder="Write some text" id="text" />
<button onClick={addTask}>Add</button>
</div>
{addtaskV.map((task) => (
<div>
<span>
{task.id} - {task.title} - {task.text}
</span>
</div>
))}
</>
);
};
export default App;
EDIT: I also suggest that you do some research on how to properly develop React forms. Although your solution works, there are better ways of doing it. But you seem to be doing well