Home > database >  React.js setState bad call Warning. { NavLink }
React.js setState bad call Warning. { NavLink }

Time:02-03

I called a function inside the style attribute.

I want to change a state value based on which NavLink is active, So I made the callback function inside the style attribute because the style callback function has a default parameter that checks if the NavLink is active or not.

<NavLink
  to="/"
  style={({ isActive }) => {
    if (isActive) {
      setActive("Home");
    }
  }}
>
  <span className={`icon `}>
    {active === "Home" ? <HouseDoorFill /> : <HouseDoor />}
  </span>
  <span className="title">Home</span>
</NavLink>

That is the warning I get.

Warning Location

I want to know if this warning is critical or not, and how can I solve this issue.

CodePudding user response:

It's that fact that you are enqueueing a state update as an unintentional side-effect during the render cycle. The style prop should be returning a React.CSSProperties style object though when used. You don't need any state here though as you can use a children render function that receives the isActive prop.

Example:

<NavLink to="/">
  {({ isActive }) => (
    <>
      <span className="icon">
        {isActive ? <HouseDoorFill /> : <HouseDoor />}
      </span>
      <span className="title">Home</span>
    </>
  )}
</NavLink>

If you must keep the active state then use an onClick handler to issue the effect of updating the React state.

<NavLink
  to="/"
  onClick={() => setActive("Home")}
>
  <span className="icon">
    {active === "Home" ? <HouseDoorFill /> : <HouseDoor />}
  </span>
  <span className="title">Home</span>
</NavLink>

See the NavLink documentation for more detail.

  • Related