Reputation: 1316
I am trying to add routing to my simple application:
import Home from './componantes/Home'
import Contact from './componantes/Contact'
import Aboutus from './componantes/Aboutus'
import { Route, Link, BrowserRouter as Router} from 'react-router-dom'
const routing = (
<Router>
<div>
<Route path="/" component={Home} />
<Router path="/contact" component={Contact} />
<Router path ="/about" component={Aboutus} />
</div>
</Router>
)
ReactDOM.render(routing, document.getElementById('root'));
but whatever url I try to access /contact
or /about
it always takes me to home component.
my aboutus componant:
import React from 'react'
export default class Contact extends React.Component{
render() {
return (
<h1>Contact componant</h1>
)
}
}
What's going wrong here?
Upvotes: 1
Views: 552
Reputation: 2595
For routes you can use Switch. Switch decide which router is called and second one is put your component in ordered way like home at the bottom.So , our app will check /contact and /about before / route.you can check more about react-router-dom on official doc.
import Home from './componantes/Home'
import Contact from './componantes/Contact'
import Aboutus from './componantes/Aboutus'
import { Route, Link, BrowserRouter as Router , Switch } from 'react-router-dom'
const App = (
<Router>
<Switch>
<Route path="/contact" component={Contact} />
<Route path ="/about" component={Aboutus} />
<Route path="/" component={Home} />
</Switch>
</Router>
)
ReactDOM.render(<App/>, document.getElementById('root')); //need to change
Upvotes: 2
Reputation: 10873
Another option is to use exact
prop for your home route, so it will be triggered only when the url is /
. Also routing
has to be a valid react component and rendered accordingly:
const Routing = () => (
<Router>
<Route exact path="/" component={Home} />
<Router path="/contact" component={Contact} />
<Router path ="/about" component={Aboutus} />
</Router>
)
ReactDOM.render(<Routing/>, document.getElementById('root'))
Upvotes: 1
Reputation: 17858
You need to add exact prop to the /
Route to tell that you only want it to match when the location matches exactly.
Also you have typos in router definition, instead of Router you need to use Route for contact and about us.
So these lines must be corrected:
<Router path="/contact" component={Contact} />
<Router path ="/about" component={Aboutus} />
<Router>
<div>
<Route path="/" exact component={Home} />
<Route path="/contact" component={Contact} />
<Route path ="/about" component={Aboutus} />
</div>
</Router>
Upvotes: 1