Created
April 24, 2020 13:12
-
-
Save rafabarbosa/4225a742fc88707c84ae7694d1fa3a6c to your computer and use it in GitHub Desktop.
Listando e atualizando lista de checkboxs
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
import React, { useState } from "react"; | |
export default function App () { | |
const [cursos, setCursos] = useState([ | |
{ name: 'zero', status: true }, | |
{ name: 'primeiro', status: true }, | |
{ name: 'segundo', status: false }, | |
{ name: 'terceiro', status: false }, | |
{ name: 'quarto', status: true }, | |
{ name: 'quinto', status: true }, | |
{ name: 'sexto', status: false }, | |
{ name: 'sétimo', status: true } | |
]); | |
const handleCheckboxChange = (index, curso) => { | |
let arrayCursos = [...cursos]; | |
arrayCursos[index].status = !curso.status; | |
setCursos(arrayCursos); | |
} | |
const handleFormSubmit = event => { | |
event.preventDefault(); | |
console.log('submit: ', cursos); | |
} | |
return ( | |
<form onSubmit={ handleFormSubmit }> | |
{ | |
cursos && cursos.map((curso, index) => ( | |
<div key={index}> | |
<input type="checkbox" name={ curso.name } checked={ curso.status } onChange={ () => handleCheckboxChange(index, curso) }/> | |
<label>{ curso.name }</label> | |
<br/> | |
</div> | |
)) | |
} | |
<br/> | |
<button type="submit">Atualizar</button> | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment