Skip to content

Instantly share code, notes, and snippets.

@verekia
Created August 3, 2019 16:15
Show Gist options
  • Save verekia/127974193dbfa18264f452ecc6db2a91 to your computer and use it in GitHub Desktop.
Save verekia/127974193dbfa18264f452ecc6db2a91 to your computer and use it in GitHub Desktop.
// @flow
import React, { useState } from 'react'
import { css } from '@emotion/core'
import toString from '@sharyn/util/toString'
import swit from '@sharyn/util/swit'
const Animal = ({
name,
numberOfLegs,
isFriendly,
}: {
name: string,
numberOfLegs?: number,
isFriendly?: boolean,
}) => {
// Hooks
const [isFavorite, setIsFavorite] = useState(false)
// Presentation, transformations to strings, handlers, no JSX
const favoriteIcon = isFavorite ? '★' : '☆'
const numberOfLegsStr = toString(numberOfLegs)
const isFriendlyStr = swit(isFriendly, [[true, 'Friendly'], [false, 'Unfriendly']])
const onStarClickHandler = () => setIsFavorite(!isFavorite)
// CSS (with Emotion)
const classes = {}
classes.pointer = css({ cursor: 'pointer' })
classes.star = css({ color: isFavorite ? 'orange' : 'black' }, classes.pointer)
classes.friendliness = css({ color: isFriendly ? 'green' : 'red' })
// JSX with basic logic only
return (
<div>
<h2>
<button css={classes.star} type="button" onClick={onStarClickHandler}>
{favoriteIcon}
</button>
{name}
</h2>
{numberOfLegsStr && (
<div>
Legs: <span css={classes.legs}>{numberOfLegsStr}</span>
</div>
)}
{isFriendlyStr && <div css={classes.friendliness}>{isFriendlyStr}</div>}
</div>
)
}
export default Animal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment