Stretch0 Stretch0 - 1 year ago 261
React JSX Question

React Router 4 Failed context type

I have plugged react router 4 into my react-create-app and upon running

npm run test
I get the following error:

Warning: Failed context type: The context `router` is marked as required in `Switch`, but its value is `undefined`.
in Switch (at App.js:17)
in main (at App.js:16)
in div (at App.js:15)
in App (at App.test.js:7)


I am using react-router@4.2.0, and react-router-dom@4.2.2

I have ensured my
<Switch>
component is nested within
<BrowserRouter>
.

App.js:

import React, { Component } from 'react';
import { Switch, Route, withRouter, Router } from 'react-router-dom';
import './App.css';

// Components
import Header from '../../components/header/Header';
import Nav from '../../components/nav/Nav';
import Dashboard from './../../containers/dashboard/Dashboard';
import Events from './../../containers/events/Events';
import NotFound from './../../containers/notfound/NotFound';

class App extends Component {
render() {
return (
<div className="App">
<Header />
<Nav />
<main id="main">
<Switch context="router">
<Route path="/" exact component={Dashboard} />
<Route path="/events" exact component={Events} />
<Route path="*" component={NotFound} />
</Switch>
</main>
</div>
);
}
}

export default App;


and my index.js

import ReactDOM from 'react-dom';
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import Store from './store';
import App from './containers/app/App';

import './index.css';

const StoreInstance = Store();

ReactDOM.render(
<Provider store={StoreInstance}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);


Anybody else come across this?

Answer Source

It is default test example of Create React App.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

Router context is provided in the 'index.js' file and doesn't exist when you run the test.

You should rewrite it next way:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './App';


it('renders without crashing', () => {
  const div = document.createElement('div');

  const StoreInstance = Store();

  ReactDOM.render(
     <Provider store={StoreInstance}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
     </Provider>, 
     div
  );
});

or move 'Provider' and 'BrowserRouter into 'App' component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download