Skip to content

Instantly share code, notes, and snippets.

@zachj0hnston
Created April 4, 2019 23:01
Show Gist options
  • Save zachj0hnston/82ff3f75e79ba732c88497a3def8193f to your computer and use it in GitHub Desktop.
Save zachj0hnston/82ff3f75e79ba732c88497a3def8193f to your computer and use it in GitHub Desktop.
Framer X Toggle
import * as React from "react"
import { useState } from "react"
import { Frame, addPropertyControls, ControlType } from "framer"
import Styled from "styled-components"
// The actual function component
export function Toggle(props) {
const [enabled, setEnabled] = useState(props.isDefaultOn)
// On click, change the state which changes the class
const handleClick = () => {
setEnabled(!enabled)
}
return (
<Container className={enabled ? "isOn" : "isOff"} onClick={handleClick}>
<Dot />
</Container>
)
}
// Add an on/off toggle in the design view
addPropertyControls(Toggle, {
isDefaultOn: {
type: ControlType.Boolean,
title: "On",
defaultValue: false,
enabledTitle: "On",
disabledTitle: "Off",
},
})
// Set the default width and height of the component
Toggle.defaultProps = {
width: 54,
height: 30,
}
// Style the outer element
const Container = Styled.div`
cursor: pointer;
position: relative;
width: 54px;
height: 30px;
padding: 4px;
background: #B8B8D6;
border-radius: 50px;
transition: background 200ms ease-in-out;
&.isOn {
background: #2A26EB;
}
`
// Style the inner element
const Dot = Styled.div`
position: absolute;
width: 22px;
height: 22px;
background: white;
box-shadow: 0px 2px 10px rgba(41, 44, 73, 0.1);
border-radius: 50px;
transition: margin-left 200ms ease-in-out;
.isOn & {
margin-left: 24px;
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment