Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been searching around the documents and various forums for a little while and I cannot seem to find any React Router component or workaround which can achieve something like this.

Similar to how we have the NavLink component, is there any component within the React Router specification which we can use to a similar degree in order to change classNames on a div element when the route matches?

For example:

<Element 
    exact to={["/one", "/two"]} 
    className="default-class" 
    activeClassName="open"
>
    <ChildComponent />
</Element>

Which defines that, when a user is on at /two or /two, it would render:

<div class="default-class open">
     <!-- child components !-->
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understood you correctly you are trying to define the className based on route. You can do it inside component using useLocation hook provided by react-router

import {useLocation} from 'react-router-rom'

const location = useLocation();


if(location =='/one'){
 return SOMETHING
}
else{
    return SOMETHING ELSE
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...