I
I
Igor2017-01-24 20:36:07
React
Igor, 2017-01-24 20:36:07

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

2 answer(s)
N
Nikita Gushchin, 2017-01-25
@Kraky

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>

Ideologically, of course, it is not very good to interfere with the styles and configuration of routes. But on the other hand: in your App component, you can get these values ​​​​without any reducers / dispatchers:
render() {
  // routes - это массив роутов для текущей локации
  // если взять за основу конфигурацию роутов, которую я привел выше,
  // то при переходе по пути /list в массиве будет два элемента.
  const { children, routes } = this.props
  const wrapperClass = (_.findLast(routes, route => !!route.wrapperClass) || {}).wrapperClass
  
  return (
    <div className={wrapperClass}>
      {children}
    </div>
  )
}

M
Maxim, 2017-01-24
@maxfarseer

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}>
...

Also, to work with classes, it is convenient to use the classnames package

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question