Arnon Rungrueng
Arnon Rungrueng

Reputation: 1

error saying TypeError: Cannot read property 'getElementById' of undefined

import React, { document } from "react";
import "./LoginandRegister.css";

function LoginandRegister() {
  const signUpButton = document.getElementById("signUp");
  const signInButton = document.getElementById("signIn");
  const container = document.getElementById("container");

  signUpButton.addEventListener("click", () =>
    container.classList.add("right-panel-active")
  );
  signInButton.addEventListener("click", () =>
    container.classList.remove("right-panel-active")
  );

Upvotes: 0

Views: 358

Answers (1)

Phoenix1355
Phoenix1355

Reputation: 1652

There are many ways to handle button interaction in React, but using getElementById and attaching event listeners is not considered normal/good practice. You should also make sure to provide any css classes to the className prop, instead of using classList.add(...), assuming that signUp, signIn, and container are all being rendered as React components or JSX.

Take a look at Handling Events in React for some inspiration on how to go about handling button clicks.

Also, importing document from the react package overrides the default document object you can use to attach event listeners. So I'd guess that it would work if you removed the import, so it just said import React from 'react'. Though I believe it's still not a proper solution and you should definitely take a look at the React documentation.

Upvotes: 3

Related Questions