Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
Javascript React Cannot read properties of null

I am trying to have a checkbox that change a className of another tag dynamically. There is my code :

import "bootstrap/dist/css/bootstrap.min.css";
class Task extends Component {
  state = {
    task: "DevApp",
  };

  isChecked = () => {
    console.log("True");
    return true;
  };
  render() {
    return (
      <React.Fragment>
        <span className="bg-warning">{this.state.task}</span>
        <label>
          <input type="checkbox" id="myCheck" />
        </label>
        <span className={this.getClassBadge()}>Done</span>]
      </React.Fragment>
    );
  }

  getClassBadge() {
    var x = document.getElementById("myCheck").checked;
    if (x) {
      return "badge m-2 bg-warning";
    } else {
      return "badge m-2 bg-primnary";
    }
  }
}

export default Task;

And i get TypeError: Cannot read properties of null (reading 'checked')

I've tried this way :

  render() {
    return (
      <React.Fragment>
        <span className="bg-warning">{this.state.task}</span>
        <label>
          <input type="checkbox" id="myCheck" />
        </label>
        <span className={this.getClassBadge()}>Done</span>]
      </React.Fragment>
      <script>
        getClassBadge() {
          var x = document.getElementById("myCheck").checked;
          if (x) {
            return "badge m-2 bg-warning";
          } else {
            return "badge m-2 bg-primnary";
          }
        }
      </script>
    );
  }


but everything is underlined in red. I would like to have a checkbox and if the checkbox is checked the next span's className will change to have a cool effect. Can someone please help me? I am sorry if it is very basic but i am only starting out :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The TypeError: Cannot read properties of null (reading 'checked') comes because when you first render, your checkbox with that id isn't mounted to the DOM yet. Because of that the document.getElementById("myCheck") returns null.

Most of the time with React you shouldn't use the document object's functions.

You should instead use React's state. Since you're using a class component, you can use this.state to have a property the value of which tells whether the checkbox is checked or not. The checkbox needs a change handler, something like

<input type="checkbox" id="myCheck" onChange={(state) => this.setState({isChecked: !state.isChecked})} />

Then in getClassBadge, simply check for the state:

return this.state.isChecked
  ? "badge m-2 bg-warning"
  : "badge m-2 bg-primnary"
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda