Last active
March 3, 2024 05:18
-
-
Save mitul-s/2cee0e5ba61793e67eddf6eaa390efa6 to your computer and use it in GitHub Desktop.
React Switch / Toggle / UI Control with Framer Motion
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 { motion } from "framer-motion"; | |
| type SwitchProps = { | |
| children: React.ReactNode; | |
| }; | |
| type ControlProps = { | |
| active: boolean; | |
| onClick: () => void; | |
| children: React.ReactNode; | |
| }; | |
| const Control = ({ active, onClick, children }: ControlProps) => { | |
| return ( | |
| <motion.li> | |
| <button | |
| type="button" | |
| role="tab" | |
| onClick={onClick} | |
| className="relative flex cursor-pointer select-none bg-transparent px-3 py-1.5 text-xs font-medium capitalize leading-none outline-none" | |
| > | |
| {active && ( | |
| <motion.div | |
| layoutId="active-control" | |
| className="absolute bottom-0 left-0 right-0 top-0 z-10 rounded bg-white shadow" | |
| /> | |
| )} | |
| <span className="relative z-20">{children}</span> | |
| </button> | |
| </motion.li> | |
| ); | |
| }; | |
| const Switch = ({ children }: SwitchProps) => { | |
| return ( | |
| <ul className="inline-flex rounded border bg-[#ECEDEB] p-px shadow-inner" role="tablist" aria-orientation="horizontal" aria-label="Switch through entry types"> | |
| {children} | |
| </ul> | |
| ); | |
| }; | |
| export { Switch, Control }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure why it's so difficult to find good code examples of building a Switch with Framer Motion, but here – this one is perfect : )