How do I get a simple change of status from a chekbox in React?

Asked

Viewed 61 times

2

Yes, rookie in React/Typescript.

Before anyone tells me to go study the material, I would like to say that I looked at different approaches to this, with different points of view, but none clarified to me the doubt that is simple, let alone left a functional code.

I would simply capture the change of state in a checkbox component, that is, if your new state is checked(checked) or unchecked(unchecked).

I tried the 4 ways below, in none of them I get success:

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

Including creating a specific handleCBA function to try to capture:

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

What I got in the treatments?

  1. First attempt: Property 'value' does not exist on type 'Eventtarget'
  2. Second attempt: Property 'checked' does not exist on type 'Eventtarget'
  3. Third attempt: As below (unless mistaken, the indicated to final to use "Event.target.checked" was just what I did on previous):
    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 state checked by accessing Event.target.checked (Boolean).
  4. Fourth attempt: It was another attempt without knowing what else to do: Type '{ id: string; name: string; control: Element; label: string; labelPlacement: "end"; checked: Boolean; onChecked: (and: Changeevent) => void; }' is not Assignable to type 'Intrinsicattributes & Formcontrollabelprops'. Property 'onChecked' does not exist on type 'Intrinsicattributes & Formcontrollabelprops'. Did you Mean 'checked'? ts(2322)

My doubt: What is the correct way to capture the change of the state in a checkbox component, i.e., get your new state marked(checked) or unchecked(unchecked). After all, what is the right way to do this? Could someone explain in a simple and direct way to the point?

Observing: I am using typescript https://material-ui.com/ but I believe there is no conflict about that.

All help is welcome!

The following is the complete code summarized for better understanding of the whole.

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;

Thank you community!

  • What is your doubt?

  • Hello novic, thank you for the return: So my question is put in the title of the question: How do I get a simple status change from a chekbox in React? In the 4 different attempts presented the pointed errors. What’s the right way to do it? (I added a highlight to the issue in the text and if you can clarify was very grateful!)

1 answer

2


To rescue the state of a checkbox create a true or false state variable (true/false) and in the checkbox configure as follows:

code:

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

and in the component:

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

where the checked={check} receives the initial value and the event onChange changes the state of this variable from false to true and vice versa.

The complete example:

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>

In the specific case of ui material on its own <FormControlLabel /> put the whole component code in control and pass the value and method as described above, example:

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"
/>

Reference: Checkbox

  • 1

    It was exactly what I need novic, I understood the way to use. Clear and objective. Show! Very grateful for the help!

  • 1

    @Marcs if it is your post reply vote as response!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.