React - toggle condition with hooks (change class upon click)

0 votes
518 views
added Aug 23, 2022 in React by lcjr First Warrant Officer (11,560 points)
edited Aug 23, 2022 by lcjr
import React from 'react'; 
import {useState} from 'react';


function BrandSlide() {
  const [isActive, setIsActive] = useState(false);

  const handleClick = event => {
    // toggle isActive state on click
    setIsActive(current => !current);
  };
  return (
    <div className={isActive ? 'brand-slide in' : 'brand-slide out'} onClick={handleClick}>
      <div className="brand-toggle"> Explore now</div>
      <div className="box">
        <img src="/images/slide_in.png" />
        Explore all our expedition gears for your need
        <a href="/expeditions" target="_blank" className="btn-slide">
          Explore now
        </a>
      </div>
  </div>
  );
  }
  export default BrandSlide;

 

1 Response

0 votes
responded Aug 24, 2022 by lcjr First Warrant Officer (11,560 points)
function MyComponent (props) {
  const [isActive, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!isActive);
  };

  return (
    <div 
      className={isActive ? 'your_className': ''} 
      onClick={toggleClass} 
    >
      <p>{props.text}</p>
    </div>
   );
}  

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...