Last active
March 22, 2019 17:43
-
-
Save maecapozzi/4c4fba317cb50c53fbc87c9ea37fc0b8 to your computer and use it in GitHub Desktop.
TypeScript example for passing a React component as a prop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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