Home > Enterprise >  Class is not added on first click
Class is not added on first click

Time:01-29

I'm trying to add dynamically class of 'active' on buttons only when they are clicked. But it doesn't work when I click first time on the second button.

const aboutText:string = 'Lorem ipsum dolor';
const [text, setText] = useState<string>('');
const btnAbout = document.getElementById('aboutDescription');
const btnExperience = document.getElementById('experienceDescription');

const handleClickAbout = () => {
    setText('aboutDescription');
    btnAbout?.classList.add('active');
    btnExperience?.classList.remove('active');
}

const handleClickExperience = () => {
    setText('experienceDescription');
    btnExperience?.classList.add('active');
    btnAbout?.classList.remove('active');
}

return (

    <button className='btn-info active' onClick={handleClickAbout} id='aboutDescription'> About </button>
    <button className='btn-info' onClick={handleClickExperience} id='experienceDescription'> Experience </button>

  <div className='description-right'>
      {(text === 'aboutDescription' || text ==='') && aboutText}
      {text === 'experienceDescription' && 'Experience'}
  </div>
)

First button at the begining has the active class, and first time when I click on the Experience button, the active class is not added. It is added on the second click. Can I solve this in some way?

CodePudding user response:

This is not how you use react. Usually when you use getElementById or classList it means you are doing something wrong

Let react manipulate DOM for you

Example:

import "./styles.css";
import clsx from "clsx";
import { useState } from "react";

export default function App() {
  const aboutText = "Lorem ipsum dolor";
  const [text, setText] = useState("");
  const isAboutActive = text === "aboutDescription" || text === "";
  const isExperienceActive = text === "experienceDescription";

  const handleClickAbout = () => {
    setText("aboutDescription");
  };

  const handleClickExperience = () => {
    setText("experienceDescription");
  };

  return (
    <>
      <button
        className={clsx("btn-info", isAboutActive && "active")}
        onClick={handleClickAbout}
      >
        About
      </button>
      <button
        className={clsx("btn-info", isExperienceActive && "active")}
        onClick={handleClickExperience}
      >
        Experience
      </button>

      <div className="description-right">
        {isAboutActive && aboutText}
        {isExperienceActive && "Experience"}
      </div>
    </>
  );
}

example on code sandbox

  • Related