Created
September 10, 2019 17:45
-
-
Save tkssharma/e87eee2732cf3880118cd952b85b34bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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