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

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

javascript - change classname of element based on route in react router

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...