Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- App.jsx
- -----------------------
- import React, { useEffect, useRef, useState } from 'react'
- import Contato from './components/Contato'
- import { v4 as uuid } from 'uuid'
- export default function App(){
- const [contato, setContato] = useState({nome: '', telefone: ''})
- const [listaContatos, setListaContatos] = useState([])
- const inputNome = useRef()
- const inputTelefone = useRef()
- function definirNome(event){
- setContato({...contato, nome: event.target.value})
- }
- function definirTelefone(event){
- setContato({...contato, telefone: event.target.value})
- }
- function adicionarContato(){
- if(contato.nome === "" || contato.telefone === "")
- return
- // se o contato jรก existe
- let duplicado = listaContatos.find((ct) => ct.nome === contato.nome && ct.telefone === contato.telefone)
- if(typeof duplicado !== 'undefined'){
- inputTelefone.current.focus()
- return
- }
- //adicionar contato ร lista
- setListaContatos([...listaContatos, contato])
- // clear
- setContato({nome: '', telefone: ''})
- // focus
- inputNome.current.focus()
- }
- function enterAdicionarContato(event){
- if(event.code === 'Enter'){
- adicionarContato()
- }
- }
- // carregar lista de contato no localstorage
- useEffect(() => {
- if(localStorage.getItem('meus_contatos') !== null){
- setListaContatos(JSON.parse(localStorage.getItem('meus_contatos')))
- }
- }, [])
- // persistencia do state (atualizar lista de contato no localstorage)
- useEffect(() => {
- localStorage.setItem('meus_contatos', JSON.stringify(listaContatos))
- }, [listaContatos])
- return (
- <>
- <h1>Minha lista de contato!</h1>
- <hr />
- <div>
- <label htmlFor="text_nome">Nome: </label><br/>
- <input type="text" id="text_nome" ref={inputNome} onChange={definirNome} value={contato.nome} />
- </div>
- <div>
- <label htmlFor="text_telefone">Telefone: </label><br/>
- <input type="text" id="text_telefone" ref={inputTelefone} onChange={definirTelefone} onKeyUp={enterAdicionarContato} value={contato.telefone} />
- </div>
- <button onClick={adicionarContato}>Adicionar contato</button>
- <hr />
- {listaContatos.map(ct => {
- return <Contato key={uuid()} nome={ct.nome} telefone={ct.telefone} />
- })}
- </>
- )
- }
- ---------------------------
- components/Contato.jsx
- ----------------------------
- import React from 'react'
- export default function Contato(props){
- return (
- <div>
- {`${props.nome} | ${props.telefone}`}
- </div>
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement