Created
April 19, 2023 07:29
-
-
Save dearshrewdwit/9361d6be4cd33df95905217764527494 to your computer and use it in GitHub Desktop.
Starting point
This file contains 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
// src/App.js | |
import { useState } from 'react' // state hook | |
import './App.css'; | |
import Task from './components/Task' | |
const initialTasks = [ | |
{ id: 1, text: 'Go shopping', completed: false }, | |
{ id: 2, text: 'Work out', completed: false }, | |
{ id: 3, text: 'See the doctor', completed: true } | |
] | |
let id = initialTasks.length | |
function App() { | |
const [tasks, setTasks] = useState(initialTasks) | |
const handleSubmit = (event) => { | |
// prevent default behaviour of event (in this case form submission event causes page to reload) | |
event.preventDefault() | |
id++ | |
// get value from first element within element that caused submission event | |
const text = event.target[0].value | |
// create a new task with the correct data | |
const newTask = { | |
id: id, | |
text: text, | |
completed: false | |
} | |
// create new state | |
const newTasks = [...tasks, newTask] | |
// tell react to update state & rerender | |
setTasks(newTasks) | |
} | |
return ( | |
<div className='App'> | |
<form onSubmit={handleSubmit}> | |
<input type="text" name="task"/> | |
<button>add task</button> | |
</form> | |
{ | |
tasks.map(item => { | |
return ( | |
<Task | |
task={item} | |
key={item.id} | |
/> | |
)}) | |
} | |
</div> | |
) | |
} | |
export default App; | |
// src/components/Task/index.js | |
import './Task.css' | |
const Task = ({task}) => { | |
return ( | |
<div> | |
<span>{task.text}</span> | |
</div> | |
) | |
} | |
export default Task | |
// src/components/Task/Task.css | |
span { | |
margin: 5px; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment