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

PropTypeDescriptionDefault Value
childrenReactNodeThe text to be highlightedundefined
durationnumberDuration of the highlight animation in seconds2
delaynumberDelay before the highlight animation begins0.5
classNamestringClass names for the highlight, add color here"bg-yellow-300"

My take on Aceternity's Hero Highlight