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:

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>
</>
);
};

Leave a Reply