もくじ
React + Reactstrap + styled-componentsでトグルスイッチを実装
トグルスイッチとは
ON/OFFやYes/Noなどをスイッチ感覚で扱えるUIです。
経緯
HTML/CSSを使ったトグルスイッチのサンプルコードはたっくさんあったのですが、styled-componentsでのサンプルコードが本当になくて苦労しました。当初styled-componentsも使いこなせていなかったので自分で一から作ることもままならず。
CSSのサンプルコードを分からないなりに地道にstyled-componentsに置き換えて完成しました。
同じように、styled-componentsでトグルスイッチを実装したい方がいれば是非参考にしてほしいです。
手順
styled-componentsとReactstrapも活用していきます。
こちらの記事もご参考ください。
1.インポート
import React from 'react' import styled from 'styled-components' import {Label, Input} from 'reactstrap'
2.定義する
const ToggleSwitch = () => { return ( <> <ToggleSwitchInput type="checkbox" id="toggle" /> <ToggleSwitchLabel for="toggle" data-on="ON" data-off="OFF" /> </> ) } export default ToggleSwitch
input
とlabel
を応用していきます。
3.スタイルの指定
const ToggleSwitchLabel = styled(Label)` cursor: pointer; position: relative; display: inline-block; margin: 10px 0; width: 80px; height: 34px; background-color: #d64141; -webkit-transition: 0.8s; transition: 0.8s; border-radius: 25px; &::before { content: ''; position: absolute; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: #fff; background-color: white; -webkit-transition: 0.6s; transition: 0.6s; border-radius: 25px; } &::after { display: block; content: attr(data-off); position: absolute; top: 4px; right: 12px; color: #fff; } ` const ToggleSwitchInput = styled(Input)` display: none; opacity: 0; &:checked + ${ToggleSwitchLabel} { background-color: #41d641; } &:checked + ${ToggleSwitchLabel}:before { -webkit-transform: translateX(46px); -ms-transform: translateX(46px); transform: translateX(46px); } &:checked + ${ToggleSwitchLabel}:after { display: block; content: attr(data-on); position: absolute; top: 4px; left: 12px; color: #fff; } `
細かい説明はいずれ更新したいと思います。
4.定義を呼び出し
手順1〜3でトグルスイッチ自体を実装できるので、あとはトグルスイッチを設置したい箇所に呼び出すだけです。
別ファイルに呼び出す場合はインポートも忘れずに。
<ToggleSwitch />
隣接セレクタの指定
セレクタを + で区切ると、同じ階層にある要素同士で、 ある要素の直後に隣接している要素を対象にスタイルを適用することができます。
h2 + p {color:#0000ff;}
これをstyled-componentsで再現するのに何日もかけて苦労したので、きちんとまとめたいな〜。
参考URL
フォーム周りで覚えておくと便利なCSS Snippets | NxWorld
styled-componentsの使い方(パッとわかりやすく、色々なパターンを説明することを目指しています) · GitHub