Special Sale - Up to23%Off!Shop Now
Blog

2025-01-27·react

Creating a Hover Preview Component with Link Interactions in React

Taher Hathi

Taher Hathi avatar

Taher Hathi

Learn how to build an interactive hover preview card that displays rich content on link hover, using React hooks and modern CSS animations for smooth UX.

Cover image

Creating hover preview components that display contextual information enriches user experience by providing instant visual feedback without disrupting navigation flow. A hover preview card with images and descriptions helps users make informed decisions before clicking, making interfaces more intuitive and efficient. This article guides you through building such a component step by step using React hooks and custom CSS.

Traditional hyperlinks in web applications lack context and visual richness. Users must click through to discover what awaits them, leading to unnecessary navigation and potential frustration. Common issues include:

  • No visual context before clicking, causing uncertainty
  • Multiple clicks needed to explore content options
  • Underutilized screen space that could show helpful previews
  • Poor discoverability of content without opening links
  • Lack of engagement compared to modern interactive interfaces

Building the Adaptive Solution

Our approach creates a floating preview card system with hoverable text links. When users hover over a link, a card appears with an image, title, and description. We'll use React hooks for state management and CSS animations for smooth transitions, creating a polished and professional result.

Key Features

The hover preview component includes several design considerations:

Hover and Display Mechanics

  • Shows preview card on mouse enter for instant feedback
  • Follows cursor position smoothly during hover
  • Hides on mouse leave with fade-out animation
  • Intelligent positioning to stay within viewport bounds

Visual and Animation Details

  • Floating card with glassmorphism backdrop blur effect
  • Smooth fade-in with scale transformation
  • Rainbow gradient underline effect on link hover
  • Staggered text animations for elegant content reveal
  • Orthogonal grid background with ambient glow

Consistent Behavior Across Devices

  • Works seamlessly with mouse on desktop
  • Responsive sizing for tablets and mobile
  • Preloads images for instant display
  • Efficient performance with optimized state updates

Implementation Details

The component uses React hooks to track active preview and cursor position, with intelligent boundary checking to keep cards visible. Here's the step-by-step breakdown:

Step 1: Set Up Your React Project

Start with a basic React or Next.js app. If using Create React App:

1npx create-react-app hover-preview-app
2cd hover-preview-app

For Next.js:

1npx create-next-app@latest hover-preview-app
2cd hover-preview-app

No additional dependencies needed—pure React with CSS!

Step 2: Prepare Preview Data

Create a data structure to hold preview information for each hoverable link:

1const previewData = {
2  figma: {
3    image: "https://images.unsplash.com/photo-1561070791-2526d30994b5?w=560&h=320&fit=crop",
4    title: "Figma",
5    subtitle: "Collaborative interface design tool",
6  },
7  sketch: {
8    image: "https://images.unsplash.com/photo-1586717791821-3f44a563fa4c?w=560&h=320&fit=crop",
9    title: "Sketch",
10    subtitle: "Vector design toolkit for Mac",

Replace these URLs with your own content images and information.

Build a reusable link component that triggers preview display:

1const HoverLink = ({
2  previewKey,
3  children,
4  onHoverStart,
5  onHoverMove,
6  onHoverEnd,
7}: {
8  previewKey: string
9  children: React.ReactNode
10  onHoverStart: (key: string, e: React.MouseEvent) => void

This component wraps text and handles hover events.

Step 4: Build the PreviewCard Component

Create the floating card that displays preview content:

1const PreviewCard = ({
2  data,
3  position,
4  isVisible,
5  cardRef,
6}: {
7  data: (typeof previewData)[keyof typeof previewData] | null
8  position: { x: number; y: number }
9  isVisible: boolean
10  cardRef: React.RefObject<HTMLDivElement | null>

Step 5: Implement State Management

Use React hooks to manage preview state and positioning:

1const [activePreview, setActivePreview] = useState<(typeof previewData)[keyof typeof previewData] | null>(null)
2const [position, setPosition] = useState({ x: 0, y: 0 })
3const [isVisible, setIsVisible] = useState(false)
4const cardRef = useRef<HTMLDivElement>(null)

Step 6: Add Image Preloading

Preload all images on mount for instant display:

1useEffect(() => {
2  Object.entries(previewData).forEach(([, data]) => {
3    const img = new Image()
4    img.crossOrigin = "anonymous"
5    img.src = data.image
6  })
7}, [])

Step 7: Implement Intelligent Positioning

Create a position update function with viewport boundary checking:

1const updatePosition = useCallback((e: React.MouseEvent | MouseEvent) => {
2  const cardWidth = 300
3  const cardHeight = 250
4  const offsetY = 20
5
6  let x = e.clientX - cardWidth / 2
7  let y = e.clientY - cardHeight - offsetY
8
9  // Keep card within horizontal bounds
10  if (x + cardWidth > window.innerWidth - 20) {

This ensures the card always stays visible within the viewport.

Step 8: Create Event Handlers

Add handlers for hover start, move, and end:

1const handleHoverStart = useCallback(
2  (key: string, e: React.MouseEvent) => {
3    setActivePreview(previewData[key as keyof typeof previewData])
4    setIsVisible(true)
5    updatePosition(e)
6  },
7  [updatePosition],
8)
9
10const handleHoverMove = useCallback(

Step 9: Add Styling and Animations

Include comprehensive CSS for layout, animations, and visual effects. Key styles include:

  • Grid background with orthogonal lines
  • Noise texture overlay for depth
  • Ambient glow with pulsing animation
  • Rainbow gradient underline for links
  • Smooth card transitions with spring easing

Accessibility Considerations

Ensure the component is accessible:

  • Use semantic HTML with proper structure
  • Add descriptive alt text for all images
  • Maintain readable contrast ratios
  • Support keyboard navigation where applicable
  • Test with screen readers for proper announcements
  • Handle focus states appropriately

Complete Implementation Code

Here's the full code for the hover preview component:

1"use client";
2
3import { useState, useCallback, useRef, useEffect } from "react"
4
5const previewData = {
6  figma: {
7    image: "https://images.unsplash.com/photo-1561070791-2526d30994b5?w=560&h=320&fit=crop",
8    title: "Figma",
9    subtitle: "Collaborative interface design tool",
10  },

Note: The component is client-side only, so use "use client" directive if using Next.js App Router.

Integration and Usage

Integrate the hover preview into your app like this:

1import HoverPreview from "./components/HoverPreview";
2
3function App() {
4  return (
5    <div>
6      <HoverPreview />
7    </div>
8  );
9}
10

Live Example

Explore Figma for collaborative interface design and real-time prototyping.

For Mac-native design try Sketch or create complete experiences with Adobe XD.

Performance and Bundle Considerations

This implementation is lightweight and efficient:

  • Pure React with no external animation libraries
  • CSS animations leverage GPU acceleration
  • Image preloading prevents layout shifts
  • Efficient state updates with useCallback hooks
  • Minimal re-renders with optimized event handling

Customization Options

Customize easily to fit your needs:

Animation Tweaks

  • Adjust transition duration and easing functions
  • Change scale values for different effects
  • Modify offset distances for card positioning
  • Add rotation or other transforms

Styling Flexibility

  • Replace grid background with custom patterns
  • Change color schemes for light/dark themes
  • Adjust card sizes and border radius
  • Customize typography and spacing

Content Structure

  • Add more preview data entries
  • Include additional metadata like tags or dates
  • Support video previews or animated GIFs
  • Integrate with CMS or API data

Best Practices and Recommendations

Follow these for optimal results:

User Testing

  • Test hover timing on different devices
  • Ensure cards don't obstruct important content
  • Verify positioning works at viewport edges
  • Check performance with many preview items

Optimization

  • Use WebP or optimized image formats
  • Implement lazy loading for large datasets
  • Profile with React DevTools for bottlenecks
  • Monitor Core Web Vitals metrics

Edge Cases

  • Handle missing images gracefully
  • Support touch devices with tap interactions
  • Consider reduced motion preferences
  • Add loading states for slow connections

Conclusion

Building a hover preview component with link interactions elevates your UI by providing contextual information instantly. By leveraging React hooks and modern CSS, you create components that enhance user experience without external dependencies. This step-by-step guide provides a solid foundation—experiment and adapt it to your projects for truly engaging interfaces.

Share this post

Creating a Hover Preview Component with Link Interactions in React | Nextjsshop Blog