Highlight Text
A component that animates highlighting text
For all the moments you need to highlight text
Installation
1
Install dependencies
npm install framer-motion tailwind-merge clsx
2
Add util file
lib/utils.ts
import { ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
3
Copy the source code
components/ui/highlight-text.tsx
'use client';
import React, { ReactNode } from 'react';
import { motion, useInView } from 'framer-motion';
import { cn } from "@/lib/utils";
interface HighlightTextProps {
children: ReactNode;
duration?: number;
delay?: number;
className?: string;
}
const HighlightText = ({
children,
duration = 2,
delay = 0.5,
className = 'bg-yellow-300',
}: HighlightTextProps) => {
const ref = React.useRef(null);
const isInView = useInView(ref, { once: true });
return (
<motion.span
ref={ref}
initial={{
backgroundSize: "0% 100%",
}}
animate={isInView ? {
backgroundSize: "100% 100%",
} : {
backgroundSize: "0% 100%",
}}
transition={{
duration,
ease: "linear",
delay,
}}
className={cn(
"relative pb-1 px-1 inline-block rounded-lg whitespace-nowrap",
className
)}
style={{
backgroundRepeat: "no-repeat",
backgroundPosition: "left center",
}}
>
{children}
</motion.span>
);
};
export default HighlightText;
Props
Prop | Type | Description | Default Value |
---|---|---|---|
children | ReactNode | The text to be highlighted | undefined |
duration | number | Duration of the highlight animation in seconds | 2 |
delay | number | Delay before the highlight animation begins | 0.5 |
className | string | Class names for the highlight, add color here | "bg-yellow-300" |
My take on Aceternity's Hero Highlight