React Router Error: You should not use Route outside of Router

I’m just doing some basic routing in my react app and I’ve done it this way before so I’m pretty confused to as why it isn’t working now.

The error I am getting says: You should not use <Route> or withRouter() outside a <Router>

I’m sure this is super basic so thanks for baring with me!

import React from 'react'
import { Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import * as BooksAPI from './BooksAPI'
import BookList from './BookList'
import './App.css'

class BooksApp extends React.Component {
  state = {
    books: []
  }

  componentDidMount() {
    this.getBooks()
  }

  getBooks = () => {
    BooksAPI.getAll().then(data => {
      this.setState({
        books: data
      })
    })
  }


  render() {
    return (
      <div className="App">
        <Route exact path="/" render={() => (
          <BookList
            books={this.state.books}
          />
        )}/>
      </div>
    )
  }
}

export default BooksApp

Answer

You need to setup context provider for react-router

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

  // ....

  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <Route exact path="/" render={() => (
            <BookList
              books={this.state.books}
            />
          )}/>
        </div>
      </BrowserRouter>
    )
  }

Side note – BrowserRouter should be placed at the top level of your application and have only a single child.