Reputation: 822
I am trying to put link in my header.js and the error occurs in index.js for some reason and i don't know how to fix it.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Header extends Component {
render() {
return (
<nav className="navbar navbar-light">
<ul className="nav navbar-nav">
<li className="nav-item">
<Link to="/">Home</Link>
</li>
<li className="nav-item">
<Link to="/profile">Profile</Link>
</li>
<li className="nav-item">
<Link to="/blog">Blog</Link>
</li>
<li className="nav-item">
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
}
export default Header
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('root'));
Error message:
6 | ReactDOM.render(, document.getElementById('root'));
Upvotes: 0
Views: 554
Reputation: 2781
The error means that you should use Link
component only in components that are inside your router. You should try and wrap the router component (BrowserRouter
or HashRouter
, depending on which one you are using) on a higher level of the components' hierarchy so that all components that need to use Link
or Route
will eventually be located under the router
in the components' tree.
If you have App
component which has Header
, Main
and Footer
components inside (as an example), and you need to access Link
in all children of App
, then you can implement it this way:
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Main from '../Main/Main';
import Header from '../Header/Header';
import Header from '../Footer/Footer';
const App = () => (
<Router>
<div>
<Header />
<Main />
<Footer />
</div>
</Router>
);
React training guide has very good examples that cover many different use cases of react router
v4.
Upvotes: 2