Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created September 10, 2019 17:45
Show Gist options
  • Save tkssharma/e87eee2732cf3880118cd952b85b34bd to your computer and use it in GitHub Desktop.
Save tkssharma/e87eee2732cf3880118cd952b85b34bd to your computer and use it in GitHub Desktop.
import ReactDOM from "react-dom";
import React, { useReducer, useRef } from "react";
const App = () => {
const inputRef = useRef();
const [items, dispatch] = useReducer((state, action) => {
switch (action.type) {
case "ADD":
return [
...state,
{
id: state.length,
name: action.payload
}
];
case "REMOVE":
return state.filter(i => i.id !== action.payload);
default:
return state;
}
}, []);
const removeItem = payload => {
dispatch({ type: "REMOVE", payload });
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch({ type: "ADD", payload: inputRef.current.value });
inputRef.current.value = '';
};
return (
<div>
<h1>TODO LIST</h1>
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
<button>Add</button>
<ol>
{items.map(({ name }, index) => {
return (
<li key={index}>
{name}
<button onClick={() => removeItem(index)}>Delete</button>
</li>
);
})}
</ol>
</form>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment