Ericgit
Ericgit

Reputation: 7073

NavLink active on same link for multiple URLs in React Router DOM

I have a page with multiple tabs (child). I also change the URL for each tab, but I'm still on the parent page, just changing the URL for the tab.

the problem is that I can't keep the parent page NavLink active when I click on the tab 'cause it changes the URL, but I want to keep that Active on the Tabs URL.

How to do this?

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

export default () => {


    return (
        <>
        <nav className='Navigation'>
            <ul className={`Navigation__list ${hide}`}>
                <li className='Navigation__list-item'> 
                   <NavLink to="/events" >Events</NavLink> 
                </li>                
            </ul>
        </nav>


        <Tabs />
       </>

    );
}

// Tabs Component As Child

    export default function Tabs () => (
                <ul className="events__tab">
                    <li> <NavLink to="/events"> All Events </NavLink> </li>
                    <li> <NavLink to="/myevents"> My Events </NavLink> </li>   
                </ul>
)

Thanks for your Support in Advance!

Upvotes: 5

Views: 9046

Answers (2)

aymane front
aymane front

Reputation: 21

add end attr in navLink

 export default function Tabs () => (
            <ul className="events__tab">
                <li> <NavLink end to="/events"> All Events </NavLink> </li> // which on same link
                <li> <NavLink to="/myevents"> My Events </NavLink> </li>   
            </ul>
)

Upvotes: 1

Ericgit
Ericgit

Reputation: 7073

All you have to do is to Write a condition inside isActive in NavLink, if the current page URL matches with defined URLs, return true otherwise false. use the function inside isActive, if it return true, you'll get active Link.. Example:

    isActive={ () => ['/example', '/exampl2'].inclues(currentPageUrl) }

if the current URL matches in the Above Array, your NavLink will be Active as long as URL doesn't match. for finding the Current Page URL use the useLocation() hook.

import React from 'react';
import { useLocation } from 'react-router-dom';

// Active the Link on two URLs

export default () => {

    // extract pathname from location
    const { pathname } = useLocation();

    return (
        <li className='Navigation__list-item'> 
            <NavLink 
                to="/events" 
                isActive={() => ['/events', '/myevents'].includes(pathname)} >
                Events 
            </NavLink> 
        </li>
    );
};

Upvotes: 20

Related Questions