Skip to content

Instantly share code, notes, and snippets.

@kaneel
Created July 3, 2018 15:19
Show Gist options
  • Save kaneel/0bafe5b2e5cb1f90fe59edf348399051 to your computer and use it in GitHub Desktop.
Save kaneel/0bafe5b2e5cb1f90fe59edf348399051 to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { styled, StyledComponentClass } from '../styled';
interface IProps {
on?: boolean;
}
interface IState {
value: boolean;
}
export const StyledToggler = styled.div`
width: 35px;
height: 18px;
padding: 3px;
position: relative;
border-radius: 10px;
box-sizing: border-box;
cursor: pointer;
transition: background 225ms ease-in-out, border-color 225ms ease-in-out;
${
({theme, on}) => `
background: ${ on ? theme.UI.togglerOnBackground : theme.UI.togglerOffBackground };
border: 1px solid ${ on ? theme.UI.togglerOnBorder : theme.UI.togglerOffBorder };
`
}
&:after {
position: absolute;
top: 50%;
content: "";
width: 13px;
height: 13px;
border-radius: 50%;
box-sizing: border-box;
transition: left 125ms ease-in-out, transform 125ms ease-in-out;
${
({theme, on}) => `
left: ${ on ? '100%' : '0%'};
transform: ${ on ? `translate3d(-15px, -50%, 0)` : `translate3d(2px, -50%, 0)`};
background: ${ on ? theme.UI.togglerOnItemBackground : theme.UI.togglerOffItemBackground };
border: 1px solid ${ on ? theme.UI.togglerOnItemBorder : theme.UI.togglerOffItemBorder };
`
}
}
` as StyledComponentClass<any, {on: boolean}>;
export default class Toggler extends React.PureComponent<IProps, IState> {
public static defaultProps: IProps = { on: false };
constructor(props: IProps) {
super(props);
this.state = {
value: !!props.on
};
}
private toggle = () => this.setState((state) => ({ value: !state.value }));
public render() {
const { value } = this.state;
return (
<StyledToggler onClick={this.toggle} on={value} />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment