Last active
March 16, 2023 21:37
-
-
Save darylwright/5a20dd74275c4de48d6f47265d3b130b to your computer and use it in GitHub Desktop.
Write easily maintainable Tailwind CSS classes with this simple tag function.
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
/* | |
This tag function enables the entry of Tailwind classes within a template string | |
without cluttering the source DOM with unnecessary whitespace. This approach is | |
better than using the `classnames` package since commas are not needed to break | |
classes into separate lines. Additionally, it's easier to organize and rearrange | |
classes within a template string compared to using `classnames`. | |
Simply copy the function below and paste it in a utilities file or another | |
location where it makes sense to be imported from. | |
You can also consider the approach demonstrated in the link below and decide | |
what's best for your use case: | |
https://www.skies.dev/tailwind-class-function | |
*/ | |
function tw(classNames: TemplateStringsArray, ...args: string[]): string { | |
return classNames | |
.concat(args) | |
.join(` `) | |
.replace(/^([^\r\n]\s)*\/\/.*$/gm, ``) | |
.replace(/\s+/g, ` `) | |
.trim(); | |
} | |
export default function FlowbiteToggle(): JSX.Element { | |
return ( | |
<label className="relative inline-flex items-center cursor-pointer"> | |
<input type="checkbox" value="" className="sr-only peer" /> | |
<div | |
className={tw` | |
w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 | |
dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 | |
// Comments and string interpolation are supported | |
peer-checked:after:translate-x-full ${`peer-checked:after:border-white`} after:content-[''] | |
after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 | |
after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 | |
peer-checked:bg-blue-600 | |
`} | |
/> | |
<span className="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">Toggle me</span> | |
</label> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment