Skip to content

Commit

Permalink
Adds solution 2 file
Browse files Browse the repository at this point in the history
  • Loading branch information
juliejonak committed Feb 8, 2020
1 parent 4a50691 commit bd8b472
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions 2. useState/solution2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

// Random ID generator
function generateId () {
return "_" + Math.random().toString(36).substr(2,9)
}

function Todo () {
const [todos, setTodos] = React.useState([])
const [input, setInput] = React.useState("")

const saveInput = (e) => setInput(e.target.value)

const addItem = () => {
setTodos( (todos) => todos.concat({
text: input,
id: generateId()
}))

setInput("")
}

const removeItem = (id) => {
setTodos( (todos) => todos.filter( (item) => item.id !== id ))
}

return (
<div>
<input
type="text"
value={input}
placeHolder="New Todo"
onChange={saveInput}
/>
<p>Input is: {input}</p>
<button onClick={addItem}>Add to list</button>

<ul>
{todos.map(({text, id}) => (
<li key={id}>
<span>{text}</span>
<button onClick={() => removeItem(id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Todo />, rootElement);

0 comments on commit bd8b472

Please sign in to comment.