Last active
March 22, 2020 20:14
-
-
Save francoisgeorgy/59941c8f64af4f72b538c079bc2730ac to your computer and use it in GitHub Desktop.
#react #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
| // Nullable values to hooks | |
| const [user, setUser] = React.useState<IUser | null>(null); | |
| // Generic Components | |
| interface Props<T> { | |
| items: T[]; | |
| renderItem: (item: T) => React.ReactNode; | |
| } | |
| function List<T>(props: Props<T>) { | |
| const { items, renderItem } = props; | |
| const [state, setState] = React.useState<T[]>([]); | |
| return ( | |
| <div> | |
| {items.map(renderItem)} | |
| </div> | |
| ); | |
| } | |
| // USAGES: | |
| ReactDOM.render( | |
| <List | |
| items={["a", "b"]} // type of 'string' inferred here | |
| renderItem={item => ( | |
| <li key={item}> | |
| {item.trim()} //allowed, because we're working with 'strings' all around | |
| </li> | |
| )} | |
| />, | |
| document.body | |
| ); | |
| ReactDOM.render( | |
| <List<number> | |
| items={[1,2,3,4]} | |
| renderItem={item => <li key={item}>{item.toPrecision(3)}</li>} | |
| />, | |
| document.body | |
| ); | |
| // Extending HTML Elements | |
| export interface IBorderedBoxProps extends React.HTMLAttributes<HTMLDivElement> { | |
| title: string; | |
| } | |
| class BorderedBox extends React.Component<IBorderedBoxProps, void> { | |
| public render() { | |
| const {children, title, ...divAttributes} = this.props; | |
| return ( | |
| //it is a DIV afterall, and we're trying to let the user use this component knowing that. | |
| <div {...divAttributes} style={{border: "1px solid red"}}> | |
| <h1>{title}</h1> | |
| {children} | |
| </div> | |
| ); | |
| } | |
| } | |
| const myBorderedBox = <BorderedBox title="Hello" onClick={() => alert("Hello")}/>; | |
| // EVENTS | |
| function eventHandler(event: React.MouseEvent<HTMLAnchorElement>) { | |
| console.log("TEST!") | |
| } | |
| const ExtendedSelectableButton = ({text, type, action}: IButtonProps) => { | |
| let [selected, setSelected] = useState(false) | |
| return (<button className={"extendedSelectableButton " + type + (selected? " selected" : "")} onClick={eventHandler}>{text}</button>) | |
| } | |
| /** This will allow you to use this event handler both, on anchors and button elements */ | |
| function eventHandler(event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>) { | |
| console.log("TEST!") | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment