I'm trying to use Link in a component outside the Router in React but i'm getting the error:
You should not use outside a
<Router>
I want to render my App component, that contains all needed subcomponents, and the HeaderIcons components, that must be shown in every page on the top. the HeaderIcons component contains a Link to a specific Route.
This is the render method in App:
render() {
return (
<Router history={browserHistory}>
<div>
<Route onEnter={this.onRouteUpdate.bind(this)} exact path="" component={Configration} />
<Route onEnter={this.onRouteUpdate.bind(this)} path="/PersonalData" component={Headerlayout} />
</div>
</Router>
);
}
onRouteUpdate(routerState) {
window.scrollTo(0, 0);
sendLocation(routerState.location);
}
ReactDom.render(<App />, document.getElementById("content"));
ReactDom.render(<HeaderIcons />, document.getElementById("configuration_icons"));
And this is the Link in HeaderIcons:
<Link
to="/PersonalData"
className="icon"
onMouseOver={this.onmouseoverHandler}
onMouseOut={this.onmouseooutHandler}>
<img src="/static/images/user.png" alt="User" />
</Link>
Is there a way to achieve this with react Router v4?
You may want to follow next approach in structuring your app. (With React-Router)
import { BrowserRouter, Switch, Route } from 'react-router-dom';
// in render method of your App component
<BrowserRouter>
<div className="app">
<HeaderComponentWithLinks> // <- see it under BrowserRouter component
<div className="content">
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage}/>
</Switch>
</div>
</div>
</BrowserRouter>
Now you will not see an error.