3

Sim, novato no React/TypeScript.

Antes que alguém diga pra ir estudar o material, gostaria de dizer que olhei diferentes abordagens a respeito, com diferentes pontos de vista, mas nenhuma me esclareceu a dúvida que é simples, e muito menos deixou um código funcional.

Gostaria simplesmente de capturar a mudança do estado em um componente checkbox, isto é, se seu novo estado é marcado(checked) ou desmarcado(unchecked).

Tentei das 4 formas abaixo, em nenhuma delas obtenho sucesso:

  1. onChange = { (e) => {setStatusAguardando(e.target.checked)} }
  2. onChange = { (e) => {setStatusAguardando(e.target.checked)} }
  3. onChange = { handleCBAguardando }
  4. onChecked = { handleCBAguardando }

Inclusive criando uma função handleCBAguardando específica para tentar capturar:

function handleCBAguardando(e: React.ChangeEvent<HTMLInputElement>) {
  setStatusAguardando(e.target.checked);
}

O que obtive nos tratamentos?

  1. Primeira tentativa: Property 'value' does not exist on type 'EventTarget'
  2. Segunda tentativa: Property 'checked' does not exist on type 'EventTarget'
  3. Terceira tentativa: Conforme abaixo (salvo engano, o indicado ao final para usar "event.target.checked" foi justamente o que fiz na anterior):
    Type '(e: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent<{}>, checked: boolean) => void'. Types of parameters 'e' and 'event' are incompatible. Type 'ChangeEvent<{}>' is not assignable to type 'ChangeEvent'. Type '{}' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 287 more.ts(2322) FormControlLabel.d.ts(41, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & FormControlLabelProps' (JSX attribute) FormControlLabelProps.onChange?: ((event: React.ChangeEvent<{}>, checked: boolean) => void) | undefined Callback fired when the state is changed. @param event The event source of the callback. You can pull out the new checked state by accessing event.target.checked (boolean).
  4. Quarta tentativa: Foi mais uma tentativa sem saber mais o que fazer: Type '{ id: string; name: string; control: Element; label: string; labelPlacement: "end"; checked: boolean; onChecked: (e: ChangeEvent) => void; }' is not assignable to type 'IntrinsicAttributes & FormControlLabelProps'. Property 'onChecked' does not exist on type 'IntrinsicAttributes & FormControlLabelProps'. Did you mean 'checked'?ts(2322)

Minha dúvida: Qual a maneira correta de capturar a mudança do estado em um componente checkbox, ou seja, obter se seu novo estado é marcado(checked) ou desmarcado(unchecked). Afinal, qual a maneira correta de se fazer isso? Alguém poderia explicar de forma simples e direto ao ponto?

Observação: Estou usando typescript@^4.2.4, e também faço da biblioteca do https://material-ui.com/ mas creio não haver conflito quanto a isso.

Toda ajuda é bem vinda!

A seguir está o código completo de forma resumida para melhor o entendimento do todo.

import React, { FormEvent, useState } from "react";
import Checkbox from '@material-ui/core/Checkbox';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';
...
function ListaAgendamentos() {
  const [statusAguardando, setStatusAguardando] = useState(true);
  const [statusConfirmado, setStatusConfirmado] = useState(false);  
  ...
  function handleCBAguardando(e: React.ChangeEvent<HTMLInputElement>) {
    setStatusAguardando(e.target.checked);
  }
  ...
  
  return (
    <div>
      <form id="buscar-lista-agendamentos" onSubmit={ buscarListaAgendamentos }>
        <Cabecalho />
        ...
        <div>
          <FormControl component="fieldset">
            <FormLabel component="legend" >Status Desejado</FormLabel>
            <FormGroup aria-label="position" row>
              <FormControlLabel
                id="status_Aguardando"
                name="status_Aguardando"
                control={<Checkbox color="primary" />}
                label="Aguardando"
                labelPlacement="end" 
                checked={statusAguardando}

                // AQUI CREIO ESTAR O PROBLEMA, NÃO CONSIGO CAPTURAR A MUDANÇA EM NENHUMA DAS FORMAS ABAIXO PARA ATRIBUIR AO MEU setStatusAguardando()
                // onChange  = { (e) => {setStatusAguardando(e.target.checked)} }  
                onChange  = { (e) => {setStatusAguardando(e.target.checked)} }
                // onChange  = { handleCBAguardando }
                // onChecked = { handleCBAguardando }
              />
        <div>
        ...
      </form>
    </div>
  );
}
export default ListaAgendamentos;

Obrigado comunidade!

2
  • Qual é a sua duvida?
    – novic
    18/07/2021 às 21:25
  • Olá novic, obrigado pelo retorno: Então, minha dúvida é o colocado no título da questão: Como pego uma simples mudança de estado de um chekbox no react? Nas 4 tentativas diferentes apresentou os erros apontados. Qual a maneira correta de se fazer isso? (adicionei um destaque à questão no texto e se puder esclarecer ficou muito grato!)
    – Marcs
    19/07/2021 às 12:15

1 Resposta 1

2

Para resgatar o estado de um checkbox crie uma variável de estado do tipo verdadeiro ou falso (true/false) e no checkbox configure da seguinte forma:

código:

const [check, setCheck] = React.useState(false);

e no componente:

<input 
  type="checkbox" 
  checked={check}
  onChange={handleChecked}
/>

onde o checked={check} recebe o valor da inicial e o evento onChange muda o estado dessa variável de falso para verdadeiro e vice-versa.

O exemplo completo:

function App() {
  const [check, setCheck] = React.useState(false);  
  const handleChecked = (e) => {
    setCheck(e.target.checked);
  }
  return (
    <div>
      <div>
        <input 
          type="checkbox" 
          checked={check}
          onChange={handleChecked}
        />
      </div>
      <div>
        Status: {check.toString()}
      </div>
    </div>
  );
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

No caso em especifico de material ui no próprio <FormControlLabel /> coloque no control todo o código do componente e nele repasse o valor e o método como descrito acima, exemplo:

const [state, setState] = React.useState({
    checkedA: true,
    checkedB: true,
    checkedF: true,
    checkedG: true,
});

const handleChange = (event) => {
    setState({ ...state, [event.target.name]: event.target.checked });
};

<FormControlLabel
    control={<Checkbox 
               checked={state.checkedA}
               onChange={handleChange} 
               name="checkedA" 
             />}
    label="Secondary"
/>

Referencia: Caixa de seleção

2
  • 1
    Era exatamente o que eu precisa novic, entendi a maneira de se usar. Claro e objetivo. Show! Muito grato pela ajuda!
    – Marcs
    19/07/2021 às 23:27
  • 1
    @Marcs se for resposta do seu post vote como resposta!
    – novic
    19/07/2021 às 23:29

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .