Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

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

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;
`;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...