react-router v4 with Typescript: how to use the `component` parameter as jsx element

580 views Asked by At

I have this component which wraps the Route component of react-router-dom:

// AuthRoute.tsx

import * as React from "react";
import { Redirect, Route } from "react-router-dom";
import { RouteProps } from "react-router";

interface Props extends RouteProps {
  user: any
}

const AuthRoute: React.SFC<Props> = ({ user, component: Component, ...rest }) => {
  console.log("auth route...", user);
  return (
    <Route {...rest} render={matchedProps => (
      !user || user.expired
        ? <Redirect to="/login"/>
        : <Component {...matchedProps} /> <--- error here
    )}/>
  );
};

The error is element type Component does not have any construct or call signatures

How can I render the Component? either with or without parameter renaming.

1

There are 1 answers

0
Amid On

I guess if you want to render passed component with some extra props you should use cloneElement for this purpose:

var elem = React.cloneElement(component, matchedProps);

So your code can look similar to this:

return (
    <Route {...rest} render={matchedProps => (
      !user || user.expired
        ? <Redirect to="/login"/>
        : React.cloneElement(component, matchedProps) 
    )}/>
  );