5

I have gone through several similar questions but could not find something that worked. I am trying to bring in BrowserRouter from react-router but it says:

Module '"../node_modules/@types/react-router"' has no exported member 'BrowserRouter'

as per another similar question on here, I did an npm install of @types/react and @types/react-router but saved as dev dependencies. they were already in my package.json but as regular dependencies. before this, they were giving a similar issue when doing import React from 'react'. It would say that those modules could not be found, same for router. then when i did the install, those errors went away but the BrowserRouter started showing this error. I did also try 'react-router-dom'.

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router';
import './App.css';

import Recipes from './components/Recipes';

const App: React.SFC = () => {

  return (
    <BrowserRouter>
      <main>
        <Switch>
          <Route exact path='/' component={Recipes} />
        </Switch>
      </main>
    </BrowserRouter>
  );
}

export default App;

Just expecting for the error to not be present and to be able to regularly navigate. This is my first time really using typescript.

Fizlo
  • 75
  • 1
  • 6

2 Answers2

3

According to the documentation of React Router, BrowserRouter gets imported from 'react-router-dom', not 'react-router'.

Here is the example code given in the link above.

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

<BrowserRouter
  basename={optionalString}
  forceRefresh={optionalBool}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}
>
  <App/>
</BrowserRouter>

Here is a SO question about the difference between react-router and react-router-dom and the accepted answer contains the following.

react-router contains all the common components between react-router-dom and react-router-native. When should you use one over the other? If you're on the web then react-router-dom should have everything you need as it also exports the common components you'll need. If you're using React Native, react-router-native should have everything you need for the same reason. So you'll probably never have to import anything directly from react-router.

dodgez
  • 551
  • 2
  • 5
  • 1
    Thank you I was very confused since I did npm i of react-router not react-router-dom. – Fizlo Sep 11 '19 at 14:18
1

I did also try 'react-router-dom'.

It should work, e.g. this code

import { BrowserRouter, Route, Switch } from "react-router-dom";

works.

Both react-dom and react-router-dom packages should be installed. That means both can be found in the dependencies section of package.json file. Working sample project using Typescript can be found here.

winwiz1
  • 2,906
  • 11
  • 24
  • Hi thank you, yes i installed react-router not react-router-dom and didnt realize the mistake lol. – Fizlo Sep 11 '19 at 14:19