Reputation: 21
I am quite new with React and l am trying to do a simple React app. I created my project using create-react-app. But I am having problem implementing Router. This is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
class App extends React.Component {
render() {
return (
<div>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
{this.props.children}
</div>
);
}
}
class Home extends React.Component {
render() {
return (
<div>
<h1>Home...</h1>
</div>
);
}
}
class About extends React.Component {
render() {
return (
<div>
<h1>About...</h1>
</div>
);
}
}
class Contact extends React.Component {
render() {
return (
<div>
<h1>Contact...</h1>
</div>
);
}
}
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute path="home" component={Home}/>
<Route path="about" component={About}/>
<Route path="contact" component={Contact}/>
</Route>
</Router>,
document.getElementById('root')
);
When I run my app, it shows me a blank page, without giving me any error/warning, like in this image:
I understood the simple use of react-router, but I am still not able to understand what is wrong with my code. Any ideas? Thanks for your answers
Upvotes: 1
Views: 1601
Reputation: 21
As Fabian Schultz suggested, since I am using react-router 4.0.0, I should use react-router-dom package instead. This fixed my issue.
Upvotes: 1
Reputation: 2601
You should not use the path property in the IndexRoute component because it is relative to its parent. I am writing a simple and clean React boilerplate, you can check it in my Github page.
To solve your problem you can replace this <IndexRoute path="home" component={Home}/>
by this <IndexRoute component={Home}/>
.
In this case the IndexRoute will use the parent path which is "/".
One more thing, I recommend you to use the component <Link />
instead of default anchor. This way you can easily set an active class to your links. Check it out.
import { IndexLink, Link } from 'react-router';
class App extends React.Component {
render() {
return (
<div>
<ul>
<IndexLink to='/' className='anchor' activeClassName='anchor--active'>Home</Link></li>
<Link to="/about" className='anchor' activeClassName='anchor--active'>About</Link></li>
<Link to="/contact" className='anchor' activeClassName='anchor--active'>Contact</Link></li>
</ul>
{this.props.children}
</div>
);
}
}
Hope it helps.
Upvotes: 0