Last active
September 18, 2021 10:18
-
-
Save ricklancee/f671362605d4e1c938f96aba668298d3 to your computer and use it in GitHub Desktop.
A simple example on how to do react stateless Higher Order Components (HOC) in typescript
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
| import * as React from 'react' | |
| import {withInjectedProp, InjectedProps} from './simple-typescript-react-stateless-hoc' | |
| interface Props { | |
| bar: string | |
| } | |
| export const ComponentWithFoo = withInjectedProp(class extends React.Component<Props & InjectedProps, State> { | |
| render() { | |
| const { foo, bar } = this.props | |
| return <div>{foo} {bar}</div> | |
| } | |
| }) |
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
| export interface InjectedProps { | |
| injected: string | |
| } | |
| type ReactHOCComponent<TProps> = React.ComponentClass<TProps> | React.StatelessComponent<TProps> | |
| export function withInjectedProp<TOriginalProps extends {}>( | |
| Component: ReactComponent<TOriginalProps & InjectedProps> | |
| ): ReactComponent<TOriginalProps> { | |
| const compWithProps: React.SFC<TOriginalProps> = (props) => ( | |
| <Component injected={'foo'} {...props} /> | |
| ) | |
| return compWithProps | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment