Home > database >  Remove all classes of children elements within div and add class to clicked div
Remove all classes of children elements within div and add class to clicked div

Time:10-28

I have the following:

(I've removed all other code and only included the relevant bit)

import { Link } from 'react-router-dom';

function Main() {
  return (
    <>
      <div id="nav">
        <Link to="/"><div id="one" ></div></Link>
        <Link to="/"><div id="two"></div></Link>
        <Link to="/"><div id="three"></div></Link>
        <Link to="/"><div id="four"></div></Link>
      </div>
    </>
  );
}

export default Main;

What I want is when the user clicks on, for example, <div id="two">, the active class is removed from <div id="one"> and added to two.

CodePudding user response:

Use the NavLink component, several of its props can consume a callback function that is passed an isActive property.

interface NavLinkProps
  extends Omit<
    LinkProps,
    "className" | "style" | "children"
  > {
  caseSensitive?: boolean;
  children?:
    | React.ReactNode
    | ((props: { isActive: boolean }) => React.ReactNode);
  className?:
    | string
    | ((props: {
        isActive: boolean;
      }) => string | undefined);
  end?: boolean;
  style?:
    | React.CSSProperties
    | ((props: {
        isActive: boolean;
      }) => React.CSSProperties);
}

Use the children function prop that accepts an isActive property that can be used to conditionally apply CSS/logic/etc to a child component.

Example:

import { NavLink } from 'react-router-dom';

...

<NavLink to="/">
  {({ isActive }) => (
    <div
      id="one"
      class={isActive ? "active" : ""}
    >
    </div>
  )}
</NavLink>
<NavLink to="/">
  {({ isActive }) => (
    <div
      id="two"
      class={isActive ? "active" : ""}
    >
    </div>
  )}
</NavLink>
...
  • Related