user16356642
user16356642

Reputation: 163

'Router' cannot be used as a JSX component

Error Message

'Router' cannot be used as a JSX component.
  Its return type 'void' is not a valid JSX element.  TS2786

 import App from './App';
    5 | 
  > 6 | ReactDOM.render(<Router />, document.getElementById('root'));

index.tsx code

ReactDOM.render(<Router />, document.getElementById('root'));

Router.tsx code

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

export default function Routes() {
  <>
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={App} />
      </Switch>
    </BrowserRouter>
  </>;
}

tsconfig

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    
  },
  "include": ["src"]
}

What is this error ?

Error in index.tsx <Router />

How do I resolve this issue?

Upvotes: 11

Views: 36103

Answers (3)

Saeid Shoja
Saeid Shoja

Reputation: 247

  1. Returning an array of JSX elements instead of a single element. To solve the error, we have to wrap the array using a React fragment or a div element.
  2. Returning any value other than a JSX element or null from a component.
  3. Having outdated versions of React typings.
# 👇️ with NPM
npm install --save-dev @types/react@latest @types/react-dom@latest
    
# 👇️ if you also want to update react and react-dom
npm install react@latest react-dom@latest
    
# ------------------------------
    
# 👇️ with YARN
yarn add @types/react@latest @types/react-dom@latest --dev
    
# 👇️ if you also want to update react and react-dom
yarn add react@latest react-dom@latest

Upvotes: 8

Wiidialga18
Wiidialga18

Reputation: 331

I would like to comment but I dont have enough reputation, But as your error code is saying you are not return anything in the Router.tsx. Try add the return statement in the Router function like so

export default function Routes() {
  return (
    <>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={App} />
        </Switch>
      </BrowserRouter>
    </>
  );
}

Upvotes: 8

Daniel M
Daniel M

Reputation: 143

Change your Router.tsx file to

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

export default function Routes() {
    return (
      <>
        <BrowserRouter>
          <Switch>
            <Route exact path="/" component={App} />
          </Switch>
        </BrowserRouter>
      </>
    )
}

Upvotes: 1

Related Questions