To play audio on hover in a React application, you can use the use-sound library, which simplifies audio management. First, install the library using npm. Then, import the sound file and the useSound Hook into your component. Attach the onMouseEnter event to the element you want to trigger the sound. When the mouse hovers over the element, the sound will play automatically, enhancing user interaction with audio feedback.
How to play sound when hovering in React
Key takeaways:
The
use-soundlibrary simplifies audio playback in React. It allows developers to play sounds in response to user actions, such as hovering over elements, by associating sounds with events likeonMouseEnter.To use
use-sound, install it via npm in your React project. Ensure your audio files are accessible in the correct paths for seamless integration.By attaching the
onMouseEnterevent handler to an element, you can trigger sound playback during hover actions. For example, hovering over a button can play a sound using theplayfunction from theuseSoundHook.Combining sound effects with visual feedback, such as color transitions on hover, enhances the user experience by offering both auditory and visual cues.
In React, we can implement sound effects on hover by using the use-sound library. This library simplifies the process of playing audio files in a React application, allowing for engaging audio feedback. By associating a specific sound with the onMouseEnter event, we can trigger the playback of the sound when an element is hovered over. This functionality enhances user interactions, providing valuable audio feedback and creating a more immersive experience within your interactive React applications.
If you want to explore more about React, check out “What is React? A tutorial on how to get started” blog on the Educative platform.
Steps to play sound on hover in React
Let’s implement the solution by setting up a React application and installing the required dependencies.
Step 1: Installing React dependencies
To get started, ensure we have a React application set up. If we don’t have one yet, we can create a new React application using the following command:
npx create-react-app soundReact
This command creates a new folder called soundReact and sets up a basic React project structure.
Next, navigate to the root directory of the React project using the terminal:
cd soundReact
Once we are in the project directory, install the
use-soundpackage usingnpm:
npm i use-sound
This command adds the use-sound library to our project, enabling us to easily manage audio playback.
Note: If you want to learn more about how to create a React application, then look into it: How to create a simple app using React
Step 2: Playing sound on hover
Below is a simple demonstration of playing an audio file when hovering over a button in React. Start by importing the necessary packages and defining the HoverSoundButton component:
import React from 'react';
import useSound from 'use-sound';
import buttonHoverSound from './hover.mp3'; // Replace with the path to your sound file
const HoverSoundButton = () => {
const soundUrl = buttonHoverSound;
const [play] = useSound(soundUrl);
return (
<button
onMouseEnter={play}
style={{
padding: '10px 20px',
fontSize: '16px',
background: '#007BFF',
border: 'none',
borderRadius: '5px',
color: '#fff',
fontWeight: 'bold',
cursor: 'pointer',
outline: 'none',
}}
>
Hover over me!
</button>
);
};
export default HoverSoundButton;Code explanation
In the above code:
Line 11: The
onMouseEnterevent handler is attached to the button. This means that when the mouse pointer enters the button’s area, it will trigger theplayfunction.
The play function comes from the useSound hook (line 7), which is initialized with the sound file specified (hover.mp3). Make sure to replace hover.mp3 with the correct path to your audio file (line 3), and then you can use the HoverSoundButton component in your main application to display the button. When the button is hovered over, it will play the sound you specified.
Note: Most browsers restrict audio playback until there’s an initial user interaction, such as a click. This means
use-soundmay not play the hover sound until the button is clicked once. After this initial interaction, it should work as expected on subsequent hovers.
Advanced example: Button with hover sound and visual feedback
The use-sound library enables us to create a button with a sound effect that plays when hovered over. The following example illustrates how to achieve this effect, dynamically triggering the sound by simply hovering over the button. Additionally, this advanced example incorporates both sound and visual feedback, including a color change on hover.
import React, { useState } from 'react';
import useSound from 'use-sound';
import hoverSound from './hover.mp3';
const SoundEffect = () => {
const soundUrl = hoverSound;
const [isButtonHovered, setIsButtonHovered] = useState(false);
const [play] = useSound(soundUrl, { volume: 0.8 });
const handleHover = () => {
if (!isButtonHovered) {
play();
setIsButtonHovered(true);
}
};
const handleMouseLeave = () => {
setIsButtonHovered(false);
};
// CSS styles for the button
const buttonStyles = {
padding: '15px',
fontSize: '24px',
background: 'transparent',
border: '2px solid #007BFF',
borderRadius: '5px',
color: '#007BFF',
fontWeight: 'bold',
cursor: 'pointer',
outline: 'none',
transition: 'background-color 0.2s, color 0.2s', // Add transition for smooth color change
};
// Styles for the button when hovered
const buttonHoverStyles = {
background: '#007BFF',
color: '#fff',
};
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<button
onMouseEnter={handleHover}
onMouseLeave={handleMouseLeave}
style={{ ...buttonStyles, ...(isButtonHovered ? buttonHoverStyles : {}) }}
>
Hover over me!
</button>
</div>
);
};
export default SoundEffect;Code explanation
In the above App.js file:
Lines 11–16: The
handleHoverfunction triggers sound playback when the button is hovered over, using theonMouseEnterevent. It also sets theisButtonHoveredstate totrueto prevent repeated playback while the button is hovered.Line 13: The
playfunction from theuseSoundhook is invoked, which plays thehover.mp3sound. This creates a delightful sound effect as the button is hovered over.
Inline styles are applied to give the button a smooth color transition, which enhances the user experience visually alongside the audio feedback.
Knowledge test
Let’s attempt a short quiz to assess your understanding.
Which React event handler is commonly used to trigger sound playback on hover?
onClick
onMouseLeave
onMouseEnter
onChange
Conclusion
Adding sound effects when hovering over elements in React using the use-sound library can greatly enhance user interactions, providing valuable audio feedback. This approach is especially useful for creating interactive React applications.
For more resources on adding audio in React applications, check out the “How to play sound in React” Answer on implementing sound effects.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
How to play audio on hover?
How to play sound in ReactJS
How do I add a song in React?
How to play and pause audio in ReactJS
How do I set a fixed audio volume upon loading React.js page, using useSound?
Free Resources