Created
January 10, 2022 08:49
-
-
Save gbersac/a5b1e1666df52bdde42508af00569ffd to your computer and use it in GitHub Desktop.
A simple toggle for react + jss
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import { createUseStyles, useTheme } from "react-jss" | |
import { Integer } from "../../model/commonTypes" | |
import { Theme } from "../../theme" | |
import { injectStyles, StylableComponent } from "./utils" | |
const useStyles = createUseStyles((t: Theme) => { | |
return { | |
lab: { | |
cursor: "pointer", | |
background: "grey", | |
display: "block", | |
position: "relative", | |
'&::after': { // create the ball and position it on the left | |
content: "''", | |
position: "absolute", | |
top: "2px", | |
left: "2px", | |
width: "calc(50% - 4px)", | |
height: "calc(100% - 4px)", | |
background: "#fff", | |
borderRadius: "50%", | |
transition: "0.3s", | |
}, | |
}, | |
inp: { | |
display: "none", | |
"&:checked + $lab:after": { // position the ball on the right if checked | |
left: "calc(100% - 2px)", | |
transform: "translateX(-100%)", | |
}, | |
}, | |
} | |
}) | |
interface Props { | |
isChecked: boolean | |
switch?: boolean | |
onChange: (newValue: boolean) => void | |
height?: Integer | |
} | |
export function Toggle(props: Props & StylableComponent) { | |
const {isChecked, switch: toggle, onChange, height} = props | |
const theme = useTheme<Theme>() | |
const css = useStyles({ theme: theme }) | |
const rHeight = height || 20 | |
return <div onClick={() => onChange(!isChecked)} {...injectStyles(props)}> | |
<input type="checkbox" className={css.inp} checked={isChecked} /> | |
<label | |
className={css.lab} | |
style={{ | |
backgroundColor: toggle ? theme.primaryBlue : isChecked ? theme.successGreen : "grey", | |
height: `${rHeight}px`, | |
width: `${rHeight * 2}px`, | |
borderRadius: rHeight, | |
}} | |
/> | |
</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment