Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda