5

Experimenting with react and I decided to test typescript.

code:

import { BrowserRouter } from 'react-router-dom'
import history  from './utilities/history'

ReactDOM.render(
  <BrowserRouter history={history}>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
)

history.js:

import { createBrowserHistory } from 'history'

export default createBrowserHistory()

error:

Type '{ children: Element; history: History; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'. Property 'history' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'.ts(2322)

package.json:

@types/react-router-dom": "^4.3.4",
react-router-dom": "^5.0.1",

When doing the exact same thing without typescript then the code works. I don't understand why this is happening, anyone that has an answer?

CodingLittle
  • 1,761
  • 2
  • 17
  • 44

2 Answers2

5

BrowserRouter doesn't take in a prop called history. See here: https://reacttraining.com/react-router/web/api/BrowserRouter. There's a Router common low-level interface which has a history prop, but it doesn't look like BrowserRouter itself accepts that. So you could consider swapping to using Router.

See this answer for some more info: https://stackoverflow.com/a/45849608/10326373

Yoni Gibbs
  • 6,518
  • 2
  • 24
  • 37
0

History can be passed to the Router interface. I had the same issue, It took me days to understand I installed and read several docs. Later I updated my code as below. I updated the react-router-dom library to version 5.3.3. I was able to pass the history to the Router and it worked.

index.tsx

import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <BrowserRouter>
        <Router history={history}>
          <App />
        </Router>
      </BrowserRouter>
  </React.StrictMode>
);

App.tsx

 <Container>
        <Switch>
        <Route exact path='/' component={HomePage} />
        <Route exact path='/catalog' component={Catalog} />
        <Route exact path='/catalog/:id' component={ProductDetails} />
        <Route exact path='/about' component={AboutPage} />
        <Route exact path='/contact' component={ContactPage} />
        <Route exact path='/server-error' component={ServerError} />
        <Route path='*' component={NotFound} />
        </Switch>
 </Container>

make sure the required packages should be in the below versions package.json

"@types/react-router-dom": "^5.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^5.3.3",