Skip to content

Instantly share code, notes, and snippets.

@francoisgeorgy
Created April 17, 2020 06:43
Show Gist options
  • Select an option

  • Save francoisgeorgy/f8463450b59d64f8a49d6628a2f06680 to your computer and use it in GitHub Desktop.

Select an option

Save francoisgeorgy/f8463450b59d64f8a49d6628a2f06680 to your computer and use it in GitHub Desktop.
#react useState with #typescript
// 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