I'm trying to build my first portfolio website and got stuck in routing using react-router-dom 4.2.2 and styled-components 2.2.3.
error message: You should not use Route or withRouter() outside a Router
I also try using Link instead of NavLink but got error too(You should not use Link outside a Router)
Someone help me please.
navigationBar.js
import React, { Component } from 'react'; import { NavigationContainer, NavItem } from './navigationBar.style'; class NavigationBar extends Component { render() { return ( <NavigationContainer> <NavItem to="/">Home</NavItem> <NavItem to="/projects">Project</NavItem> </NavigationContainer> ); } } export default NavigationBar;
navigationBar.style.js
import styled from 'styled-components'; import { Flex, Div } from 'theme/grid'; import { NavLink } from 'react-router-dom'; export const NavigationContainer = styled(Flex)` position: fixed; right: 20px; top: 0.5em; font-size: 1em; `; export const NavItem = styled(NavLink)` position: relative; padding-left: 10px; cursor: pointer; `;
To fix the 'You should not use Route or withRouter() outside a Router' error with React Router v4, we should wrap our app with the BrowserRouter component. import { BrowserRouter } from "react-router-dom"; ReactDOM. render( <BrowserRouter> <App /> </BrowserRouter>, document. getElementById("root") );
withRouter is a higher order component that will pass closest route's match , current location , and history props to the wrapped component whenever it renders. simply it connects component to the router. Not all components, especially the shared components, will have the access to such router's props.
You can get access to the history object's properties and the closest <Route> 's match via the withRouter higher-order component. withRouter will pass updated match , location , and history props to the wrapped component whenever it renders.
Protected routes are those routes that only grant access to authorized users. This means that users must first meet certain conditions before accessing that specific route. For instance, your application can require only logged-in users be able to visit the dashboard page.
Make sure you wrap the main react render code in the Router. For example, with react-dom you need to wrap the app in Browser-Router. If this is a Udacity project, this is typically the index.js file.
import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter> , document.getElementById('root'));
Well you're using a NavLink outside of the BrowserRouter/HashRouter (whatever you're using)
You said it yourself
You should not use Link outside a Router
Make sure that you have the structure like this
// App render or whatever render() { return ( <BrowserRouter> <NavigationBar /> {`whatever else you doin'`} </BrowserRouter> ); }
You must always render them inside a Router
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With