Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active December 2, 2022 14:13
Show Gist options
  • Save karol-majewski/74e85f34531155182f1b9a9c2984e18e to your computer and use it in GitHub Desktop.
Save karol-majewski/74e85f34531155182f1b9a9c2984e18e to your computer and use it in GitHub Desktop.
The easiest way to use generic Props<T>
import * as React from 'react';
enum Tao { Yin, Yang }
interface Props<T> {
value: T;
onClick(value: T): void;
}
class GenericClassComponent<T> extends React.Component<Props<T>> {
handleClick = () => {
const { value, onClick } = this.props;
onClick(value)
}
render() {
return <div onClick={this.handleClick}>{JSON.stringify(this.props.value)}</div>
}
}
import * as React from 'react';
enum Tao { Yin, Yang }
interface Props<T> {
value: T;
onClick(value: T): void;
}
function GenericFunctionComponent<T>(props: Props<T>) {
const { value, onClick } = props;
const handleClick = React.useCallback(() => {
onClick(value)
}, [value, onClick])
return <div onClick={handleClick}>{JSON.stringify(value)}</div>
}
<GenericFunctionComponent value={Tao.Yin} onClick={value => console.log(value)} />
@karol-majewski
Copy link
Author

karol-majewski commented Dec 2, 2022

A pleasant yet somewhat unexpected benefit of using a function expression instead of React.FunctionComponent to define GenericFunctionComponent is that assigning static properties just works. No extra definitions are needed.

Example:

declare const SubComponent: React.FunctionComponent;

GenericFunctionComponent.SubComponent = SubComponent;

I can now use it as:

<GenericFunctionComponent>
  <GenericFunctionComponent.SubComponent />
</GenericFunctionComponent>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment