Last active
December 2, 2022 14:13
-
-
Save karol-majewski/74e85f34531155182f1b9a9c2984e18e to your computer and use it in GitHub Desktop.
The easiest way to use generic Props<T>
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
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> | |
} | |
} |
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
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)} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A pleasant yet somewhat unexpected benefit of using a function expression instead of
React.FunctionComponent
to defineGenericFunctionComponent
is that assigning static properties just works. No extra definitions are needed.Example:
I can now use it as: