Skip to content

Instantly share code, notes, and snippets.

@dmjcomdem
Created March 21, 2019 03:13
Show Gist options
  • Save dmjcomdem/9a5205357069a512a7dff6d4ddc4499d to your computer and use it in GitHub Desktop.
Save dmjcomdem/9a5205357069a512a7dff6d4ddc4499d to your computer and use it in GitHub Desktop.
function App() {
const [value, setValue] = React.useState("");
const [data, setData] = React.useState([]);
const handlerChange = ({ target: { value } }) => {
setValue(value);
};
const handlerKeyPress = event => {
if (event.key === "Enter") {
setData([...data, value]);
setValue("");
}
if (!value && event.key === "Backspace") {
setData([...data.slice(0, data.length - 1)]);
}
};
const handlerRemove = index => () => {
setData([...data.slice(0, index), ...data.slice(index + 1)]);
};
return (
<div className="App">
<input
type="text"
value={value}
onChange={handlerChange}
onKeyUp={handlerKeyPress}
/>
{data.map((item, index) => (
<p key={`${index}-${item}`}>
{item}
<button onClick={handlerRemove(index)}>X</button>
</p>
))}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment