Last active
October 9, 2021 17:51
-
-
Save markopostma/41843c8f7b1886b5bc1ee2f40e064d34 to your computer and use it in GitHub Desktop.
Multiple reusable layouts in Typescript with React Router v4
This file contains hidden or 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
| /** | |
| * DESCRIPTION: | |
| * | |
| * A Route component that extends the default react-router-dom Route. | |
| * By default a Route component uses the MainLayout component as defined below. | |
| * | |
| * EXAMPLE USAGE: | |
| * | |
| * <Switch> | |
| * <Route path="/" exact component={Home} /> | |
| * <Route path="/login" component={Login} layout={EmptyLayout} /> | |
| * </Switch> | |
| */ | |
| import * as React from 'react' | |
| import { Route as DomRoute, RouteProps as DomRouteProps } from 'react-router-dom' | |
| /** Default layout */ | |
| class MainLayout extends React.Component { | |
| render() { | |
| return ( | |
| <div className="main-layout"> | |
| <header /> | |
| {this.props.children} | |
| <footer /> | |
| </div> | |
| ) | |
| } | |
| } | |
| /** Empty layout */ | |
| class EmptyLayout extends React.Component { | |
| render() { | |
| return ( | |
| <div className="empty-layout"> | |
| {this.props.children} | |
| </div> | |
| ) | |
| } | |
| } | |
| interface RouteProps extends DomRouteProps { | |
| layout?: React.ComponentClass | |
| } | |
| class Route extends DomRoute<RouteProps> { | |
| static defaultProps: RouteProps = { | |
| layout: MainLayout, | |
| } | |
| render() { | |
| const { layout, component, path, exact } = this.props | |
| return ( | |
| <DomRoute | |
| path={path} | |
| exact={exact} | |
| render={props => { | |
| return React.createElement( | |
| layout!, | |
| props as React.Attributes, | |
| React.createElement(component!, props) | |
| ) | |
| }} | |
| /> | |
| ) | |
| } | |
| } | |
| export default Route |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment