steveruizok
4/30/2019 - 9:42 AM

Switch Tutorial Finished Component

Switch Tutorial Finished Component

// [1]
import * as React from "react"
import { Frame, addPropertyControls, ControlType } from "framer"

// [2]
type Props = {
    isOn: boolean
    onValueChange: (isOn: boolean) => any
}

// [3]
export function Switch(props: Props) {
    // [4]
    const [state, setState] = React.useState({
        isOn: props.isOn,
    })

    // [5]
    React.useEffect(() => {
        setState({
            isOn: props.isOn,
        })
    }, [props.isOn])

    // [6]
    const handleTap = () => {
        props.onValueChange(!state.isOn)
        setState({
            isOn: !state.isOn,
        })
    }

    // [7]
    return (
        <Frame
            height={50}
            width={80}
            center
            borderRadius={25}
            // [8]
            onTap={handleTap}
            variants={{
                off: { background: "#BBBBBB" },
                on: { background: "#0070DF" },
            }}
            transition={{
                type: "tween",
                duration: 0.2,
            }}
            initial={props.isOn ? "on" : "off"}
            animate={state.isOn ? "on" : "off"}
        >
            <Frame
                size={46}
                top={2}
                left={2}
                borderRadius={"100%"}
                background="#FFFFFF"
                variants={{
                    off: { x: 0 },
                    on: { x: 30 },
                }}
                transition={{
                    type: "tween",
                    duration: 0.2,
                }}
            />
        </Frame>
    )
}

// [9]
Switch.defaultProps = {
    isOn: false,
    onValueChange: () => null,
    height: 50,
    width: 80,
}

// [10]
addPropertyControls(Switch, {
    isOn: {
        type: ControlType.Boolean,
        title: "Is On",
    },
})