You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react

JongHun Lee picture JongHun Lee · Nov 15, 2017 · Viewed 66.9k times · Source

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;
`;

Answer

Bruce Seymour picture Bruce Seymour · May 7, 2018

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'));