IlanZiin

#036 LISTA DE TAREFAS

Sep 15th, 2022
1,059
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useRef } from 'react'
  2.  
  3. function App(){
  4.  
  5.     // state
  6.     const [listaTarefas, setListaTarefas] = useState(() => { return [] })
  7.     const [tarefa, setTarefa] = useState(() => { return '' })
  8.  
  9.     // ref
  10.     const idTarefa = useRef(0)
  11.     const inputRef = useRef()
  12.  
  13.     // methods
  14.     function adicionarTarefa(){
  15.         setListaTarefas(old => {
  16.             return [...old, {id: idTarefa.current, texto: tarefa}]
  17.         })
  18.         idTarefa.current++;
  19.         setTarefa('')
  20.         inputRef.current.focus()
  21.     }
  22.  
  23.     function limparTarefas(){
  24.         setListaTarefas([])
  25.         idTarefa.current = 0
  26.     }
  27.  
  28.     function removerTarefa(id){
  29.         const tmp = listaTarefas.filter(tarefa => tarefa.id !== id)
  30.         setListaTarefas(tmp)
  31.     }
  32.  
  33.     return (
  34.         <>
  35.             <h1>Gestor de tarefas</h1>
  36.             <hr />
  37.             <input ref={inputRef} type="text" value={tarefa} onChange={e => { setTarefa(e.target.value) }} />
  38.             <div>
  39.                 <button onClick={adicionarTarefa}>Adicionar</button>
  40.                 <button onClick={limparTarefas}>Limpar tudo</button>
  41.             </div>
  42.             <hr />
  43.             <p>Tarefas: </p>
  44.             {listaTarefas.map((t) => {
  45.                 return <p key={t.id}>{t.texto} - <span style={{cursor: 'pointer'}} onClick={ () => { removerTarefa(t.id) } }>[remover]</span></p>
  46.             })}
  47.         </>
  48.     )
  49. }
  50.  
  51. export default App
Advertisement
Add Comment
Please, Sign In to add comment