Home > database >  dynamic route appending throw error with typescript
dynamic route appending throw error with typescript

Time:10-13

I am getting following error when i try for dynamically loading the route

  return (
TS2739: Type '{ children: Element[]; }' is missing the following properties from type 'RouterProps': location, navigator
     8 |     <BrowserRouter>
  >  9 |       <Router>
       |        ^^^^^^
    10 |         {allModules.map((m: ModuleProps) => {
    11 |           return <Route path={m.routeProps.path} element={m.routeProps.element} key={m.name} />;
    12 |         })}

prop type:

export interface ModuleProps {
  name: string;
  routeProps: { path: string; element: React.ReactElement };
}

page:

import { FC } from 'react';

const Login: FC = () => {
  return <div>Login</div>;
};

export default {
  name: 'Login',
  routeProps: { path: '/login', element: <Login /> },
};

Module:

import LoginModule from './login';

export default [LoginModule];

App:

import { ModuleProps } from '@stonehenge-props/api-interfaces';
import { FC } from 'react';
import { BrowserRouter, Route, Router, RouterProps } from 'react-router-dom';
import allModules from './modules';

export const App: FC<RouterProps> = () => {
  return (
    <BrowserRouter>
      <Router>
        {allModules.map((m: ModuleProps) => {
          return <Route path={m.routeProps.path} element={m.routeProps.element} key={m.name} />;
        })}
      </Router>
    </BrowserRouter>
  );
};

export default App;

index:

import { StrictMode } from 'react';
import * as ReactDOMClient from 'react-dom/client';

import App from './app/app';

const root = ReactDOMClient.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

CodePudding user response:

The low-level Router component has a couple non-optional props that need to be passed, but you probably meant to import and render Routes instead of another Router component.

Also, since App isn't consuming any props there's no need to declare them in the function typing. Remove RouterProps from the declaration. Use either const App: React.FC<{}> = () => {} or just simply const App = () => {}.

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import allModules from './modules';

export const App: FC<{}> = () => {
  return (
    <BrowserRouter>
      <Routes>
        {allModules.map((m: ModuleProps) => {
          return (
            <Route
              path={m.routeProps.path}
              element={m.routeProps.element}
              key={m.name}
            />
          );
        })}
      </Routes>
    </BrowserRouter>
  );
};

Edit dynamic-route-appending-throw-error-with-typescript

  • Related