これからにStylingはemotionでキマリ☆2019/08/07 React勉強会 #11
View Slide
⾃⼰紹介Twitter@kam1nchu職種インフラエンジニアフロントエンドエンジニア歴Javascript歴 3年React歴 3年AWS歴 半年 2
ReactのStylingは何使ってますか?3
emotionが盛り上がってきています4
他のに⽐べて何がいいのか5
CSS Modulessassとか書けたりはする。CSSとJSの間での定数の共有ができない。import styles from "./styles.css";export const StyledButton = () => (Styled!);6
Inline Styles⼿軽なので好きだけど、hoverとかできないことがある。cssのサンプルのコピペとかし難い。const styles = {background: "#fff",padding: "20px",borderRadius: "5px",border: "none",};export const StyledButton = (props) => (Styled!);7
Styled-Components⼀⾒便利そうだけど...import styled from "styled-components";export const StyledButton = styled.button`background: ${props => props.selected ? "#fff" : "#ed3330"};padding: 20px;border-radius: 5px;border: none;`;8
Styled-Components毎回Component作らされるの、⾯倒くさくないですか?import styled from "styled-components";const StyledTable = styled.table``;const StyledTh = styled.th``;const StykedTr = styled.tr``;export const Table = () => (カラムカラム値値);9
そこで10
emotion11
inlineな感じで書ける/** @jsx jsx */import { jsx } from "@emotion/core";export const StyledComponent = (props) => {return ();};12
Styled-Componentsみたいなこともできるimport styled from "@emotion/styled";export const StyledButton = styled.button`color: turquoise;`;13
AltCSSっぽいこともできる/** @jsx jsx */import { jsx, css } from "@emotion/core";const styled = css`color: blue;header & {color: green;}`;export const StyledComponent = () => (Green TextBlue Text); 14
emotion(+typescript+parcel)の導⼊の仕⽅15
⾊々⼊れる#ビルドyarn add -D typescript parcel-bundler# reactyarn add -D @types/react @types/react-domyarn add react react-dom# emotionyarn add @emotion/core @emotion/styled16
tsconfig.json(当然reactなので)、jsx記法でReact.createElementになるように設定npx tsc --init//略"jsx": "react"//略17
基本的なもの揃えるファイル構成はこんな感じ│├ node_modules├ src├ index.html├ App.tsx # ReactDOM.renderとかする└ components└ SomeComponent.tsx # emotionで作る├ package.json├ yarn.lock└ tsconfig.json18
componentを作る実は、emotionのcomponentだけはReact.createElementを使わず、JSX Pragmaでempotionの関数を指定する。/** @jsx jsx *///↑これをemotion使うcomponentのファイルに毎回書くimport { jsx, css } from "@emotion/core";export const SomeComponent = () => ();19
確認するtypescript+parcelなら特に設定はいらないparcel src/index.html20
おわり21