Answer the question
In order to leave comments, you need to log in
How to correctly add a class to a page component?
There is a website running on react+redux+react-router. All pages have a common layout, which is described in the App component. A situation arises when it is necessary to add classes to the wrapper block (in the App component) when going to different pages. For example (block .wrapper), on page list should be class .wrapper--list, on pages wrapper--pages. How to do it right? Now it happens like this - there is a reducer (dom.js), it has all the necessary state for classes. When the page component is loaded, this happens: dispatch ({type: CHANGE_WRAPPER ....})
But it seems to me that it is somehow suboptimal to update the entire state every time just to change the class. Are there any practical options?
Answer the question
In order to leave comments, you need to log in
If your router is not version 4, then you can try adding the wrapperClass property to the routes
<Route path="/" component={App}>
<Route path="list" component={ListComponent} wrapperClass="wrapper--list" />
</Route>
render() {
// routes - это массив роутов для текущей локации
// если взять за основу конфигурацию роутов, которую я привел выше,
// то при переходе по пути /list в массиве будет два элемента.
const { children, routes } = this.props
const wrapperClass = (_.findLast(routes, route => !!route.wrapperClass) || {}).wrapperClass
return (
<div className={wrapperClass}>
{children}
</div>
)
}
I can’t say “good / bad / how best”, because I don’t see the whole example, but if we want to do it “somehow else”, then we can use the location
object
For example:
generateClassNames() {
if (location.href.indexOf('list') {
return '.wrapper--list'
}
...
}
...
render()
....
let myClass = this.generateClassNames()
...
<div classNames={myClass}>
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question