Reactjs dynamic classname with react router

- 1 answer

Ad

I have a navigation and each item's class becomes active when the path is matched.
ex)
when path is http://localhost/food
<li class="active">food</li>

What is the best clean way to achieve this with ES6 syntax, React, React Router?
I don't want to use Flux or Redux only because of this... if i need to, then i want to know how to do it with Redux (because flux is more complicating and has some issues)

app.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link } from 'react-router';

import Home from './components/Home';
import Projects from './components/Projects';
import Blog from './components/Blog';
import createBrowserHistory from 'history/lib/createBrowserHistory';

class App extends React.Component {
  render() {
    return (
      <div>
        <div className="header">
          <nav className="navbar">
            <div className="navbar-header">
              <ul className="right">
                <li>
                  <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="projects">PROJECTS</a>
                </li>
                <li>
                  <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="blog">BLOG</a>
                </li>
                <li>
                  <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="/">YOOCHAN</a>
                </li>
              </ul>
            </div>
          </nav>
        </div>
        <div className="container">{this.props.children}</div>
      </div>
    );
  }
}

let documentReady = () => {
  ReactDOM.render(
    <Router history={createBrowserHistory()}>
      <Route component={App}>
        <Route path="/" component={Home} />
        <Route path="projects" component={Projects} />
        <Route path="Blog" component={Blog} />
      </Route>
    </Router>, document.getElementById('app')
  );
};

$(documentReady);

package.json

  "devDependencies": {
    "babel-core": "^6.3.21",
    "babel-eslint": "^5.0.0-beta6",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "eslint": "^1.10.3",
    "eslint-config-airbnb": "^2.1.1",
    "eslint-loader": "^1.1.1",
    "eslint-plugin-react": "^3.12.0",
    "history": "^1.17.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3",
    "react-router": "^1.0.3",
    "webpack": "^1.12.9"
  }
Ad

Answer

Ad

By using the Link helper of react-router

<Link className="class" activeClassName="active" to="/path">Path</Link>

Link to docs https://github.com/rackt/react-router/blob/latest/docs/API.md#link

Ad
source: stackoverflow.com
Ad