Created
April 17, 2020 06:43
-
-
Save francoisgeorgy/f8463450b59d64f8a49d6628a2f06680 to your computer and use it in GitHub Desktop.
#react useState with #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
| // empty initial state | |
| const [pill, setPill] = useState<'red' | 'blue'>(); | |
| // JSX: {pill && <span>You chose {pill.toUpperCase()} pill!</span>} | |
| // clearable state | |
| export const PillSelector: React.FunctionComponent = () => { | |
| const [pill, setPill] = useState<'blue' | 'red' | undefined>('blue'); // <-- | |
| return (<div> | |
| <button onClick={() => setPill('red')}>Red pill</button> | |
| <button onClick={() => setPill('blue')}>Blue pill</button> | |
| // 🛑 Argument of type 'undefined' is not assignable | |
| // to parameter of type 'SetStateAction<string>'. | |
| <button onClick={() => setPill(undefined)}>Reset</button> | |
| {pill && <span>You chose {pill.toUpperCase()} pill!</span>} | |
| </div>); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment