Visual feedback is a crucial part of user interaction design. One way to enhance this experience is by changing the appearance of icons when users hover over them. In this blog, we’ll explore how to implement a Like icon that changes on hover using React (Next.js) and styled-components, with a focus on how Next.js handles SVG imports.
Why Use SVGs?
SVGs (Scalable Vector Graphics) are ideal for icons due to their scalability and ability to look sharp on any screen size. Additionally, SVGs are easily styled with CSS, making them perfect for dynamic changes such as hover effects.
Setting Up the Project
We’ll start by setting up a Next.js project and integrating styled-components.
npx create-next-app my-app
cd like-icon-example
npm install styled-components
Creating the Like Icon Component
Next, we’ll create a Like.js component using styled-components to manage the default and hover states of our Like icon.
Like.js
// Like.js "use client"; // Import Libraries import React from "react"; import styled from "styled-components"; // Import Images import likeDefault from "./images/likeDefault.svg"; import likeHover from "./images/likeHover.svg"; // CSS-in-JS const Icon = styled.div` display: inline-block; width: 40px; height: 40px; cursor: pointer; background-image: url(${likeDefault.src}); background-size: cover; transition: background-image 0.3s ease; &:hover { background-image: url(${likeHover.src}); } `; const Like = () => { return ( <> <Icon /> </> ); }; export default Like;
Using the Like Icon in a Next.js Page
Now that our Like.js component is ready, let’s implement it in a Next.js page.
page.js:
// page.js import Like from "./Like"; export default function Home() { return ( <> <Like /> </> ); }
Output:
How It Works
- Default State: Initially, the background-image is set to likeDefault.svg, displaying a grey Like icon.
- Hover State: On hover, the background-image switches to likeHover.svg, revealing a red Like icon.
The smooth transition between these states is achieved through the transition property, which animates the change over 0.3s with an ease timing function.
Also Read: Understanding CSS Transitions with Timing Functions
Conclusion
This example shows how to implement different SVG images for default and hover states using styled-components in a React (Next.js) project. Leveraging Next.js’s handling of static assets, like SVGs, ensures that paths are managed correctly, optimizing the build process.
By combining SVGs with CSS transitions, you can create visually appealing hover effects that enhance user interaction. You can further extend this concept by adding additional states such as focus or active, making your components even more interactive and accessible.
Add comment