when I type something in the input field and press Enter key on keyboard I want to add that item on the list automatically, once when is added I want to clear the input field too. I think I should use useRef when I press Enter but not sure how to do it?
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
const initialList = [
{
id: "a",
name: "Robin",
},
{
id: "b",
name: "Dennis",
},
];
const AppAddItem = () => {
const [list, setList] = useState(initialList);
const [name, setname] = useState("");
const handleChange = (event) => {
setname(event.target.value);
};
const handleAdd = () => {
const newList = list.concat({ name, id: uuidv4() });
setList(newList);
setname("");
};
return (
<div>
<AddItem name={name} onChange={handleChange} onAdd={handleAdd} />
<List list={list} />
</div>
);
};
const AddItem = ({ onChange, name, onAdd }) => {
return (
<div>
<div>
<input type="text" value={name} onChange={onChange} />
<button type="button" onClick={onAdd}>
Add
</button>
</div>
</div>
);
};
const List = ({ list }) => {
return (
<form>
{list.map((item) => {
return <li key={item.id}>{item.name}</li>;
})}
</form>
);
};
export default AppAddItem;