How to build a font family toggle with Next.js, Tailwind CSS and Framer Motion
Recently, I want to build a font family toggle to switch between monospace and sans-serif font family.
The reason
Why using monospaced fonts?
Fixed-width characters are lovable.
Why is it necessary to toggle font family?
Readers are more generally more accustomed to Sans-Serif fonts.
Monospace fonts can be space inefficient.
There are 3 steps to implement it:
Choose and set the desired font families.
Toggle font family.
Make this toggle prettier by adding some animation.
Set the font family
First, import the fonts you like using next/font.
Here I use "Inter" and "JetBrains Mono".
next/font can be used with Tailwind CSS through a CSS variable.
And it's easy for us of theming.
Finally, add these CSS variables to the Tailwind CSS config.
You can now use the font-sans and font-mono utility classes to apply the font to your elements.
Font Family toggle
Toggle font-family is just a dynamic style change, or you can call it theming.
Sounds familiar, right?
The well-known next/themes provides us with a great example of how to store global theme information and implement support for multiple themes.
next/themes uses a <ThemeProvider> to warp the content (examples).
It calls the API useContext of React to passing data deeply into the tree and updating data passed via context.
And the theme status is stored in the localStorage.
Therefore, this article also follows the next/themes in implementing font-family toggle.
Animation
Here we use two different interaction methods:
On desktop devices, we use a button to toggle the font family;
On mobile devices, we use a layout switch for toggling.
This article uses framer motion to power the animation.
SVG Morphing
First, we should prepare two SVGs to indicate the font family.
SVG for Sans-Serif
SVG for Monospace
Then, the next step is morphing the SVGs with Flubber.js
and animating them with Framer Motion.
Here we can control the path of the SVG using pathIndex passed from the parent component.
Layout Animation
Layout animations is quite simple using Framer Motion.
Conclusion
The full code is wrapped up here: source code.
And the final effect is shown as follows.
Regrettably, the font switch can cause a layout shift in some cases.
And this seems to be unavoidable.