How can I dynamically update className with React js?

228 Views Asked by At

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?

2

There are 2 best solutions below

4
Nury Amandurdyev On BEST ANSWER

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

The React components rerender, based on the state. So you sould use your state to define the className instead of a boolean.

When your state changes the component will re-render.

Try this:

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

  function handleClick() {
    setToggleClass((prevState) => prevState == "active" ? "passive" : "active" );
  }

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