Ad
Conditionally Set Active Class On Menu Using React Router Current Route
I am using react router 1.0.2 and my routes look like this:
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="triangles" component={Triangles}/>
</Route>
</Router>
</Provider>,
document.querySelector('.container')
);
My App component looks like this and I thought I could pass the location in the props:
import React, {Component} from 'react';
import Menu from './menu';
export default class App extends Component {
render() {
return (
<div>
<Menu/>
<div className="jumbotron">
{this.props.children && React.cloneElement(this.props.children, {
location: this.props.location
})}
</div>
</div>
);
}
};
I want to conditionally set an active class on the Menu component:
import React, {Component} from 'react';
import { pushPath } from 'redux-simple-router';
import { Link } from 'react-router';
export default class Menu extends Component {
render() {
return (
<nav role="navigation" className="navbar navbar-default">
<div id="navbarCollapse" className="collapse navbar-collapse">
<ul className="nav navbar-nav">
<li className={this.props.location.pathname === '/' ? 'active' : ''}>
<Link to="/">Home</Link>
</li>
</ul>
</div>
</nav>
);
}
};
But the this.props.location
is null when the menu's render function is called?
How can I pass props to child components?
Ad
Answer
It doesn't look like you're passing the prop into the correct element. The children
of App
would be whatever child route is being rendered (so either Home
or Triangles
), but you want the prop to be passed to Menu
.
To do that, just pass it in via JSX:
import React, {Component} from 'react';
import Menu from './menu';
export default class App extends Component {
render() {
return (
<div>
<Menu location={this.props.location} />
<div className="jumbotron">
{this.props.children}
</div>
</div>
);
}
};
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad