Icon swap
Cross-fades between two glyphs on an infrequent state change.
For a glyph that changes on an occasional action: copy to copied, star to starred. state is the key, so change it together with the child. The first render does not animate, and under reduced motion the glyphs fade without scale or blur.
Copy button
"use client"
import * as React from "react"
import { CheckIcon, CopyIcon } from "@keyline-icons/react"
import { Button } from "@/components/ui/button"
import { IconSwap } from "@/components/ui/icon-swap"
export default function IconSwapCopyButton() {
const [copied, setCopied] = React.useState(false)
React.useEffect(() => {
if (!copied) return
const timer = setTimeout(() => setCopied(false), 2000)
return () => clearTimeout(timer)
}, [copied])
async function copy() {
await navigator.clipboard.writeText("https://example.com/invite/4f9k2")
setCopied(true)
}
return (
<>
<Button variant="outline" size="icon" aria-label="Copy the invite link" onClick={copy}>
<IconSwap state={copied ? "copied" : "idle"}>{copied ? <CheckIcon /> : <CopyIcon />}</IconSwap>
</Button>
<span role="status" className="sr-only">
{copied ? "Copied" : null}
</span>
</>
)
}
Favourite toggle
"use client"
import * as React from "react"
import { StarIcon } from "@keyline-icons/react"
import { StarIcon as StarFilledIcon } from "@keyline-icons/react/fill"
import { IconSwap } from "@/components/ui/icon-swap"
import { Toggle } from "@/components/ui/toggle"
export default function IconSwapFavouriteToggle() {
const [starred, setStarred] = React.useState(false)
return (
<Toggle variant="outline" aria-label="Star the project" pressed={starred} onPressedChange={setStarred}>
<IconSwap state={starred ? "starred" : "idle"}>{starred ? <StarFilledIcon /> : <StarIcon />}</IconSwap>
</Toggle>
)
}
Installation
npx shadcn@latest add @khaeli/icon-swapbunx --bun shadcn@latest add @khaeli/icon-swapInstall @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.
Installs with
- npm packages
- motion ^12.23.12
Keyboard
EnterSpace- Activate the control around the icon; the swap follows its state.
IconSwapitself takes no focus.
Accessible name
- The swap is visual only. Name the control with text or an
aria-label, and keep that name the same in both states. - Say the new state another way:
aria-pressedon a toggle, or arole="status"message such as Copied for a one-off action.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/icon-swap.json