はじめに
今回はstyled-componentsのThemeに焦点を当てていきたいと思います。
themeに関しては実務で使った事がなく、あまり理解できていないところもあるので、詳しい方コメントで教えていただけると幸いです^_^
他のstyled-componentsの記事はこちら
themeとは?
ReduxみたいにProviderで囲ったコンポーネント内のどこからでもアクセスできる値みたいなイメージです。
styled-componentsドキュメント引用↓
// Define our button, but with the use of props.theme this timeconstButton=styled.button` color: ${props=>props.theme.fg}; border: 2px solid ${props=>props.theme.fg}; background: ${props=>props.theme.bg}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; `;// Define our `fg` and `bg` on the themeconsttheme={fg:"palevioletred",bg:"white"};// This theme swaps `fg` and `bg`constinvertTheme=({fg,bg})=>({fg:bg,bg:fg});render(<ThemeProvidertheme={theme}><div><Button>DefaultTheme</Button> <ThemeProvidertheme={invertTheme}><Button>InvertedTheme</Button> </ThemeProvider> </div> </ThemeProvider> );
themeのメリット
themeというぐらいなので、色を全体的に変えたりなどスタイルの雰囲気をガラッと変えたりするのに使いやすそうです。
実際に使ってみる
ドキュメントの例でも十分ですが、せっかくなので使ってみましょう!index.tsx
にAppProviderコンポーネントを作って、ボタンを押したらthemeが切り替わる感じにします。
AppコンポーネントはThemeProviderで挟んで、themeを渡します。これでAppコンポーネント内ではt hemeが使えます。
importReact,{useState}from'react';importReactDOMfrom'react-dom';import{ThemeProvider}from'styled-components';import{App}from'./App';constAppProvider=()=>{const[is_theme_dark,set_is_theme_dark]=useState(false);constdefault_theme={text_color:'black',background_color:'white',}constdark_theme={text_color:'white',background_color:'black'}consttoggle_theme=()=>{set_is_theme_dark(!is_theme_dark);};return(<><buttononClick={toggle_theme}>Change!</button>
<ThemeProvidertheme={is_theme_dark?dark_theme:default_theme}><App/></ThemeProvider>
</>
);};ReactDOM.render(<AppProvider/>,document.getElementById('app'));
次にAppコンポーネントことApp.tsx
に以下のコードを書きます。
importReact,{useContext}from'react';importstyled,{ThemeContext}from'styled-components';exportconstApp=()=>{consttheme=useContext(ThemeContext);return(<TitleWrapper><h1>HelloWorld!</h1>
<Button>NoEvent</Button>
</TitleWrapper>
);};constTitleWrapper=styled.div`
width: 100vw;
height: 100vh;
background-color: ${(props)=>props.theme.background_color};
text-align: center;
h1 {
color: ${(props)=>props.theme.text_color};
}
`;constButton=styled.button`
color: ${(props)=>props.theme.text_color};
background-color: ${(props)=>props.theme.background_color};
`;
themeはhooksのuseContextにstyled-componentsからインポートしたThemeContextを渡してあげるとindex.tsxで定義したthemeの値が入ります。そしてテーマの値をスタイルに使っています。
ブラウザを見てみると下の画像のようにdefault_themeが表示されると思います。
左上のボタンを押すとdark_themeに変わります。
使ってみた感想
今回は簡単な物を作ったのであまり恩賜を受けられませんでしたが、グローバルステートと組み合わせて、サイト全体のテーマを変えたりするのに使えそうな感じがしました。
ここまで読んでいただきありがとうございます!今後もいろいろな記事を書いていきたいと思っているので感想や要望などいただけたら、モチベーションにもつながります。