reactjsreact-router-domtailwind-cssflowbite

React Router DOM + Flowbite NavBar: problem with links


I would like to use React Router DOM alongside Flowbite React. I am trying to build a navbar.

import {Link, useLocation} from "react-router-dom";
import {Navbar} from "flowbite-react";
...
const location = useLocation();
...
<Link to="/page">
    <Navbar.Link active={location.pathname === "/page"}>
        Link
    </Navbar.Link>
</Link>

It works, but I got warnings:

react-dom.development.js:86 Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.

I understand why it happens (because Link and Navbar.Link both contain <a>), but I have no idea how to fix these warnings.


Solution

  • I found a solution in the usage of useLinkClickHandler:

    import {useLinkClickHandler, useLocation} from "react-router-dom";
    import {Navbar} from "flowbite-react";
    
    export interface AppNavLinkProps {
        to: string;
        text: string;
    }
    
    export default function AppNavLink(props: AppNavLinkProps) {
        const location = useLocation();
        const clickHandler = useLinkClickHandler(props.to);
        
        return <span onClick={clickHandler}>
            <Navbar.Link href={props.to} active={location.pathname === props.to}>
                {props.text}
            </Navbar.Link>
        </span>;
    }
    ...
    <AppNavLink to="/page" text="Link" />
    

    In that way I can get rid of Link and leave only Navbar.Link, but preserve Link functionality (don't reload a page when the link was clicked, but use History API).