0% found this document useful (0 votes)
8 views4 pages

Hook Method Todo

The document contains a React component that implements a simple item list application. Users can add items to the list and remove them, with proper state management using hooks. The code also includes input validation to prevent adding empty items and displays a message when the list is empty.

Uploaded by

tanvertawsan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Hook Method Todo

The document contains a React component that implements a simple item list application. Users can add items to the list and remove them, with proper state management using hooks. The code also includes input validation to prevent adding empty items and displays a message when the list is empty.

Uploaded by

tanvertawsan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

import React, { useState } from 'react'

const App = () => {


return (

const [list, setList]=useState([]);

const [item, setItem]=useState("");

const AddToList= ()=> {


list.push(item)
setList (value[...list]);
};

const RemoveItem = (index) => {


list.splice(index,:1);
setList([...list])

};

<div>

<table>
<tbody>
{
list.length!==0(

list.map((element,index)=>{
return(
<tr>
<td>{element}</td>
<td>
<button onClick={()=>{
RemoveItem(index)
}}>
Remove
</button>
</td>
</tr>
)

})
):(<tr></tr>)
}
</tbody>
</table>

<input onChange={(e)=>setItem(e.target.value)}
placeholder='item'/>
<button>Add</button>
</div>
)
}

export default App


import React, { useState } from 'react';

const App = () => {


const [list, setList] = useState([]);
const [item, setItem] = useState("");

const AddToList = () => {


if (item.trim() !== "") { // Prevent adding empty items
setList([...list, item]); // Correctly update the state with the
new item
setItem(""); // Clear the input after adding
}
};

const RemoveItem = (index) => {


const updatedList = list.filter((_, i) => i !== index); // Create a
new list without the removed item
setList(updatedList); // Update the state
};

return (
<div>
<table>
<tbody>
{list.length > 0 ? (
list.map((element, index) => (
<tr key={index}>
<td>{element}</td>
<td>
<button onClick={() =>
RemoveItem(index)}>Remove</button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="2">No items in the list</td>
</tr>
)}
</tbody>
</table>

<input
value={item} // Bind input to state
onChange={(e) => setItem(e.target.value)}
placeholder="Enter an item"
/>
<button onClick={AddToList}>Add</button>
</div>
);
};

export default App;

You might also like