reactjsreact-router-domviteswc

I have a problem when working with react-router-dom version 6


Here is the problem, first this project is generated using vite. I have the error that says Warning: React does not recognize the activeStyle prop on a DOM element. That is a first few lines from the error. I issue comes up when I add the activeStyle prop in the NavLink component from react-router-dom which should be its built-in prop however react does not recognize that as a valid prop, how could that be ? Do you have any idea whats happening ?

here is the component in the project that contains the eror:

Header.jsx

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

const Header = () => {
  return (
    <div className="header">
      <NavLink to="/" activeStyle={{ fontWeight: "bold", color: "red" }}>
        Home
      </NavLink>

      <NavLink to="/about" activeStyle={{ fontWeight: "bold", color: "red" }}>
        About
      </NavLink>
    </div>
  );
};

export default Header;

vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import sass from "sass";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],

  css: {
    preprocessorOptions: {
      sass: {
        implementation: sass,
      },
    },
  },
});

here is the snapshot of the error in the console: enter image description here


Solution

  • there's no activeStyle prop but there's the regular style prop that doesn't behave as it would do in a regular component where you would pass the styles object to it

    it works slightly different with the navlink component as it works as a render prop where you would pass a callback function and the navlink component will take care of the styling you can read more about it from here https://reactrouter.com/en/main/components/nav-link

    here's an example

      const styles = {
        fontWeight: "bold",
        textDecoration: "underline",
        color: "#161616",
      };
    
    
    
    <nav className="header-nav">
            <NavLink
              style={({ isActive }) => (isActive ? styles : null)}
              to="/Host"
            >
              Host
            </NavLink>
    

    also by default, an active class is added to a component when it is active so you can use CSS to style it.

    .header-nav a.active {
    font-weight: bold;
    text-decoration: underline;
    color: #161616; }