はじめに
今回はstyled-componentsの簡単な使い方をやります。
他のstyled-componentsの記事
* styled-componentsでJavascriptの値を使う
* styled-componentsのThemeを使ってみる
* styled-componentsでレスポンシブを楽に書く
styled-componentsとは?
styled-componentsはReactにおけるCSSの当て方の一つで、Reactのコンポーネントのようにjsの値を渡したりでき、コンポーネントのようにスコープが作られるため、使いやすいです。
インストール
Reactの環境ができている方は下のコマンドはスルーしてください。
できていない方は以下のコマンドを打つか、記事を見ながら作ってみてください。
typescriptを使わない場合は下のコマンドの--typescriptは必要ありません。
npx create-react-app --typescript [アプリ名]
webpackでReact+Typescriptの環境構築をする
VSCodeで開き、ターミナルで以下のコマンドを打ちます。Typescriptを使わない場合は@types/styled-componentsは必要ありません。
//npm
npm install --save styled-components
npm install --save-dev @types/styled-components
//yarn
yarn add styled-components
yarn add -D @types/styled-components
準備完了!
実際に使ってみる
早速使ってみましょう!
普通にスタイルを当てる
まずはApp.tsxに以下のコードを書いてブラウザで見てみましょう。
importReactfrom'react';exportconstApp=()=>{return<h1>HelloWorld!</h1>;
};ちなみにindex.tsxは以下のようにしています。
importReactfrom'react';importReactDOMfrom'react-dom';import{App}from'./App';ReactDOM.render(<App/>,document.getElementById('app'));次にstyled-componentsを使って、スタイルを当ててみましょう。
以下のような感じで使います。
VSCodeの拡張機能のvscode-styled-componentsを入れるとシンタックスハイライトが効いてみやすくなります。
const[コンポーネントとして使う名前]=styled.[タグ名]`
//style
`;App.tsxにstyled-componentsをインポートして、h1にスタイルを当てています。
importReactfrom'react';importstyledfrom'styled-components'exportconstApp=()=>{return<Title>HelloWorld!</Title>;
};constTitle=styled.h1`
color: red;
`;補足:下のコードように連想配列で書く書き方もあるみたいです。詳しくはドキュメント
constBox=styled.div({background:'palevioletred',height:'50px',width:'50px'});コンポーネント内の要素にスタイルを当てる
App.tsxを以下のように書き換えてみましょう。
importReactfrom'react';importstyledfrom'styled-components';exportconstApp=()=>{return(<TitleWrapper><h1>HelloWorld!</h1>
</TitleWrapper>
);};constTitleWrapper=styled.div`
text-align: center;
h1 {
color: red;
}
`;中心に赤くHello World!が表示されるはずです。
上のようにある要素の中の要素にスタイルを当てるといった使い方もできます。
擬似要素を使う
App.tsxを以下のように書き換えてみましょう。
importReactfrom'react';importstyledfrom'styled-components';exportconstApp=()=>{return(<TitleWrapper><h1>HelloWorld!</h1>
<Button>Hover</Button>
</TitleWrapper>
);};constTitleWrapper=styled.div`
text-align: center;
h1 {
color: red;
}
`;constButton=styled.button`
color: white;
background-color: blue;
&:hover {
background-color: skyblue;
}
`;先ほどに加えて、hoverで水色になるボタンが表示されます(hover前は青)。
&の後に擬似要素を書くことで使えます。
コンポーネントにスタイルを当てる
App.tsxを以下のように書き換えてみましょう。
importReactfrom'react';importstyledfrom'styled-components';exportconstApp=()=>{return(<TitleWrapper><h1>HelloWorld!</h1>
<Button>Hover</Button>
<StyledButton>Hover</StyledButton>
</TitleWrapper>
);};constTitleWrapper=styled.div`
text-align: center;
h1 {
color: red;
}
`;constButton=styled.button`
color: white;
background-color: blue;
&:hover {
background-color: skyblue;
}
`;constStyledButton=styled(Button)`
color: black;
background-color: white;
`;上では色だけを変えたボタンを新しく作っています。このように、作ったコンポーネントに上書きする形でスタイルを当てる事ができます。
MaterialUIなどにも使う事ができて便利です。
ここまで読んでいただきありがとうございます!少しでもお役に立てれば幸いです!