Skip to content

Instantly share code, notes, and snippets.

@maecapozzi
Last active March 22, 2019 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maecapozzi/4c4fba317cb50c53fbc87c9ea37fc0b8 to your computer and use it in GitHub Desktop.
Save maecapozzi/4c4fba317cb50c53fbc87c9ea37fc0b8 to your computer and use it in GitHub Desktop.
TypeScript example for passing a React component as a prop
// Sometimes you want to be able to pass a React component as a prop. One reason you might want to do this is routing.
// Imagine you want to create a special kind of route that can't be reached unless a user is logged in.
// A `<PrivateRoute />` component might be used like this:
// This component lets you see your user profile, but only after you have logged in.
// App.tsx
const App = () => (
<Router>
<Homepage path="/" />
<PrivateRoute as={Profile} path="/profile" />
</Router>
);
// And this is how `<PrivateRoute />` might be implemented
// PrivateRoute.tsx
import React from "react";
import { AuthContext } from "../contexts/AuthContext";
import { Homepage } from "../pages/Homepage";
type Props = {
path: string;
};
type PrivateProps = {
as: React.ComponentType<Props>;
path: string;
};
export class PrivateRoute extends React.Component<PrivateProps, {}> {
static contextType = AuthContext;
render() {
const Component = this.props.as;
return this.context.isLoggedIn ? (
<Component {...this.props} />
) : (
<Homepage path="/" />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment