React 搭配 Styled-Components 用 Checkbox 客製 Toggle Switch Button

Angel
Its Ok to Make Mistakes
6 min readApr 3, 2019

Toggle Switch Button

第一步:先確定 React Styled-Component 開發環境設定完成

可以參考:使用 Create-React-App 建構 React Styled-Components 及 Sass 開發環境

第二步:在 Template 使用 Wrapper 將 Checkbox 和 CheckBoxLabel 包在一起,在 CheckBox type 為 checkbox,以及任意 id, 讓 CheckBoxLabel 可以指向該 id。

!!! 在 CheckBoxLabel 一般於 html 使用 for 在 React 要使用 htmlFor 取代

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const App = () => {
return (
<div>
<CheckBoxWrapper>
<CheckBox id="checkbox" type="checkbox"/>
<CheckBoxLabel htmlFor="checkbox"/>
</CheckBoxWrapper>
</div>
)
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

第三步:CheckBoxLabel 的部分,使用 label 畫出 Toggle Switch Button 的外形,CheckBox 使用 input 來製作點擊切換,設定透明度為 0,大小與 CheckBoxLabel 一致,並將 CheckBox 與 CheckBoxLabel 重疊。

const CheckBoxWrapper = styled.div`
position: relative;
`
const CheckBoxLabel = styled.label`
position: absolute;
top: 0;
left: 0;
width: 42px;
height: 26px;
border-radius: 15px;
background: #BEBEBE;
cursor: pointer;
`;
const CheckBox = styled.input`
opacity: 0;
z-index:1;
border-radius: 15px;
width: 42px;
height: 26px;
`;

設定點擊 CheckBox 的時候切換背景顏色。

const CheckBox = styled.input`
opacity: 0;
z-index:1;
border-radius: 15px;
width: 42px;
height: 26px;
&:checked + ${CheckBoxLabel} {
background: #4FBE79;
}
`;

使用 CSS 偽元素製作出可以切換的圓形按鈕於 CheckBoxLabel 及 CheckBox。並設定切換轉換的 transition 秒數。

const CheckBoxWrapper = styled.div`
position: relative;
`;
const CheckBoxLabel = styled.label`
position: absolute;
top: 0;
left: 0;
width: 42px;
height: 26px;
border-radius: 15px;
background: #bebebe;
cursor: pointer;
&::after {
content: "";
display: block;
border-radius: 50%;
width: 18px;
height: 18px;
margin: 3px;
background: #ffffff;
box-shadow: 1px 3px 3px 1px rgba(0, 0, 0, 0.2);
transition: 0.2s;
}
`;
const CheckBox = styled.input`
opacity: 0;
z-index: 1;
border-radius: 15px;
width: 42px;
height: 26px;
&:checked + ${CheckBoxLabel} {
background: #4fbe79;
&::after {
content: "";
display: block;
border-radius: 50%;
width: 18px;
height: 18px;
margin-left: 21px;
transition: 0.2s;
}
}
`;

輸出後完成

Say hello! 我是 Angel,這裏的內容如果有幫到你,希望能獲得一些拍手作為鼓勵 
工作上的合作歡迎隨時透過 Mail 聯繫我 contact@aneglho.design

Thanks for watching!

--

--

Angel
Its Ok to Make Mistakes

A web / UIUX designer, in digital entertainment industry, Taipei Taiwan.