Peter Foo
Peter Foo

Reputation: 3

How to fix: ReactDOM.render() - TS2345: Argument of type '() => Element' is not assignable to parameter of type 'ReactElement'

I'm learning React-Router with typescript and coming into a typing issue.

I was running on an older version of react and react-router. I've updated to the latest builds with yarn.

import * as ReactDOM from "react-dom";
import AppRouter from "./routers/app-router";

ReactDOM.render(AppRouter, document.getElementById("app"));
import {
  Route,
  Link,
  BrowserRouter,
  Switch,
  NavLink
} from "react-router-dom";

const MainPage = () => <div>This is my mainpage.</div>;


const Header = () => (
  <header>
    <h1>Hello</h1>
    <NavLink to="/" activeClassName="is-active" exact={true}>
      Main
    </NavLink>
  </header>
);

const AppRouter = ()  => (
  <BrowserRouter>
    <div>
      <Header />
      <Switch>
        <Route path="/" component={MainPage} exact={true} />
      </Switch>
    </div>
  </BrowserRouter>
);

export default AppRouter;

As far as I understand ReactDOM.render() takes in 2 elements. My const AppRouter is of the Element type. Why am I getting a type error from ReactDOM.render()?

Upvotes: 0

Views: 1803

Answers (1)

Shanon Jackson
Shanon Jackson

Reputation: 6541

ReactDOM.render(<AppRouter/>, document.getElementById("app"));

This should do the trick let me know if it doesn't, The problem is AppRouter isn't a valid React.ReactElement untill its constructed through a React.createElement call which is what happens behind the scenes when JSX syntax is used.

<AppRouter/> will now become React.createElement(ApppRouter); which will return the correct type React.ReactElement;

Upvotes: 1

Related Questions