Skip to content

Instantly share code, notes, and snippets.

@mitul-s
Last active March 3, 2024 05:18
Show Gist options
  • Select an option

  • Save mitul-s/2cee0e5ba61793e67eddf6eaa390efa6 to your computer and use it in GitHub Desktop.

Select an option

Save mitul-s/2cee0e5ba61793e67eddf6eaa390efa6 to your computer and use it in GitHub Desktop.
React Switch / Toggle / UI Control with Framer Motion
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 };
@mitul-s
Copy link
Author

mitul-s commented Mar 3, 2024

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 : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment