react router v4 error Link component

Mamen Source

i have component that import a Link from react-router-dom

import React, { Component } from 'react';
import { Link } from 'react-router-dom';


class Sidebar extends Component{

  render() {
    return (
      <div className="be-left-sidebar">
        <div className="left-sidebar-wrapper"><a href="#" className="left-sidebar-toggle">Blank Page</a>
          <div className="left-sidebar-spacer">
            <div className="left-sidebar-scroll">
              <div className="left-sidebar-content">
                <ul className="sidebar-elements">
                  <li className="divider">Menu</li>
                  <li className="parent"><a href="#"><i className="icon mdi mdi-home" /><span>Home</span></a>
                    <ul className="sub-menu">
                      <li><Link to='/'>Home</Link>
                      </li>

                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div className="progress-widget">
            <div className="progress-data"><span className="progress-value">60%</span><span className="name">Current Project</span></div>
            <div className="progress">
              <div style={{width: '60%'}} className="progress-bar progress-bar-primary" />
            </div>
          </div>
        </div>
      </div>
    );
  }

};

export default Sidebar;

then console.log shows an error

  • Warning: Failed context type: The context router is marked as required in Link, but its value is undefined.
  • Cannot read property 'history' of undefined

`

i am new in react and i am using react router v4.1.1

anyone can help me? thanks

javascriptreactjsreact-router

Answers

answered 1 year ago Vishal Gulati #1

In React router v4, we have Switch, Route and Link components that we import from react-router-dom and configure our router as follows:

import { Switch, Route, Link } from 'react-router-dom';

  <span>LINKS:</span>
  <ul>
    <li onClick={this.props.goToDefault}><Link to={'/'}>Go To Default</Link></li>
    <li onClick={this.props.goToSub1}><Link to={'/left-sub1'}>Go To One</Link></li>
    <li onClick={this.props.goToSub2}><Link to={'/left-sub2'}>Go To Two</Link></li>
  </ul>
  <Switch>
    <Route exact path='/' component={LeftSubDefault} />
    <Route path='/left-sub1' component={LeftSubOne} />
    <Route path='/left-sub2' component={LeftSubTwo} />
  </Switch>

In the app.js or whatever your entry file is. Wrap your App component inside BrowserRouter as follows:

import { BrowserRouter } from 'react-router-dom';

<BrowserRouter>
    <App />
</BrowserRouter>

Here is a wonderful article that may help.

answered 1 year ago philippsh #2

Make sure you have your component appearing inside <Router> component.

comments powered by Disqus