Search code examples
reactjsreact-router-dombrowser-history

Property 'history' does not exist on type 'IntrinsicAttributes


I'm wrapping react app in Router with passing createBrowserHistory prop. But getting "property 'history' does not exist on type 'IntrinsicAttributes & RouterPops"

Here is my index.tsx

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Router } from "react-router-dom";
import history from "../src/utils/history";

ReactDOM.render(
    <Router history={history}>
    <App />
  </Router>,
  document.getElementById("root")
);

Here is my history.tsx

import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;

I'm using react-router-dom v6.0.2


Solution

  • I suspect you could implement a bit more of the logic of one of the higher level routers and get the behavior you want with a custom history object.

    BrowserRouter implementation for example:

    export function BrowserRouter({
      basename,
      children,
      window
    }: BrowserRouterProps) {
      let historyRef = React.useRef<BrowserHistory>();
      if (historyRef.current == null) {
        historyRef.current = createBrowserHistory({ window });
      }
    
      let history = historyRef.current;
      let [state, setState] = React.useState({
        action: history.action,
        location: history.location
      });
    
      React.useLayoutEffect(() => history.listen(setState), [history]);
    
      return (
        <Router
          basename={basename}
          children={children}
          location={state.location}
          navigationType={state.action}
          navigator={history}
        />
      );
    }
    

    Create a CustomRouter that consumes a custom history object and manages the state:

    const CustomRouter = ({ history, ...props }) => {
      const [state, setState] = useState({
        action: history.action,
        location: history.location
      });
    
      useLayoutEffect(() => history.listen(setState), [history]);
    
      return (
        <Router
          {...props}
          location={state.location}
          navigationType={state.action}
          navigator={history}
        />
      );
    };
    

    Edit property-history-does-not-exist-on-type-intrinsicattributes