Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I dynamically update className with React js?

I have a Collection component and when I click on a div in this component, I want to change both the className of the Collection component and the className of the first sibling component after the Collection component.

With UseState, I could only change the className of the component I was in.

My Collection.js looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Collection = () => {
  const [toggleClass, setToggleClass] = useState(false);

  function handleClick() {
    setToggleClass((toggleClass) => !toggleClass);
  }

  let toggleClassCheck = toggleClass ? "passive" : "active";

  return (
    <React.Fragment>
      <div className={`step ${toggleClassCheck}`}>
        <div className="atrium">
          <span>Collection</span>
        </div>
        <div className="content">
          <div
            className="moreThenOne"
            area="collectionTitle"
            onClick={handleClick}
          >

Can anyone help me on how to do the process I mentioned above?

>Solution :

I didn’t quite understand what you want, but if you want to impact sibling of component "Collection" executing function inside of "Collection" you definitely should try "ref". Via useRef hook.

export const Collection = () => {
const [toggleClass, setToggleClass] = useState(false);
const divRef = useRef(null);

function handleClick() {
  divRef.current.nextSibling.classList.toggle('active');
  divRef.current.nextSibling.classList.toggle('passive');
  setToggleClass((toggleClass) => !toggleClass);
}

let toggleClassCheck = toggleClass ? 'passive' : 'active';

return (
<>
  <div className={`step ${toggleClassCheck}`} ref={divRef}>
    <div className="atrium">
      <span>Collection</span>
    </div>
    <div className="content">
      <div className="moreThenOne" onClick={handleClick}>
        CLICK ZONE
      </div>
    </div>
  </div>
</>
);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading