Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useRef } from 'react'
- function App(){
- // state
- const [listaTarefas, setListaTarefas] = useState(() => { return [] })
- const [tarefa, setTarefa] = useState(() => { return '' })
- // ref
- const idTarefa = useRef(0)
- const inputRef = useRef()
- // methods
- function adicionarTarefa(){
- setListaTarefas(old => {
- return [...old, {id: idTarefa.current, texto: tarefa}]
- })
- idTarefa.current++;
- setTarefa('')
- inputRef.current.focus()
- }
- function limparTarefas(){
- setListaTarefas([])
- idTarefa.current = 0
- }
- function removerTarefa(id){
- const tmp = listaTarefas.filter(tarefa => tarefa.id !== id)
- setListaTarefas(tmp)
- }
- return (
- <>
- <h1>Gestor de tarefas</h1>
- <hr />
- <input ref={inputRef} type="text" value={tarefa} onChange={e => { setTarefa(e.target.value) }} />
- <div>
- <button onClick={adicionarTarefa}>Adicionar</button>
- <button onClick={limparTarefas}>Limpar tudo</button>
- </div>
- <hr />
- <p>Tarefas: </p>
- {listaTarefas.map((t) => {
- return <p key={t.id}>{t.texto} - <span style={{cursor: 'pointer'}} onClick={ () => { removerTarefa(t.id) } }>[remover]</span></p>
- })}
- </>
- )
- }
- export default App
Advertisement
Add Comment
Please, Sign In to add comment