How to play sound with checkbox in React

Key takeaways:

  • The use-sound library simplifies playing audio in React, enabling developers to add interactive sound effects with minimal code.

  • Customize checkbox behavior to play different sounds for checked and unchecked states. Use audio feedback to confirm actions, improving accessibility and usability.

  • Import audio files for the “checked” and “unchecked” states and manage playback using the useSound Hook.

  • Hide the default checkbox input and style it using custom elements, ensuring accessibility while enhancing visual appeal.

  • Use playOn and playOff functions from useSound to trigger sound effects based on the checkbox state.

  • Audio cues improve accessibility by providing feedback to users with visual impairments or those relying on auditory signals for interaction confirmation.

In React applications, sound feedback can make user interactions more engaging by providing audio cues for various actions. By integrating the use-sound library in React, we can enhance checkbox interactions with sound, which is especially useful for accessibility. Audio feedback helps users understand when an action, like checking or unchecking a checkbox, has been completed.

Consider reading the detailed blog, “React hooks design patterns and creating components without class,” to get familiar with core concepts like functional components and Hooks. This foundational knowledge will help you better understand the concepts discussed in this Answer.

In this Answer, we’ll learn how to implement sound feedback for checkbox interactions using the useSound Hook in React.

Installing React dependencies

  • To get started, we need to have a React application ready. If we don’t have one set up, we can create a new React app using the following command:

npx create-react-app soundReact
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
  • Once the app is created, navigate to the project’s root directory. We’ll install the use-sound library using npm, a simple React hook that lets you play sounds easily.

cd soundReact
npm i use-sound
Installing sound package in React

Ensure you have two audio files in your project folder. For example, we’ll use click-button.mp3 for the “checked” sound and pop.mp3 for the “unchecked” sound.

Coding example

The following code demonstrates how to use the use-sound library in React to play sound effects when a checkbox is checked or unchecked.

import React, { useState } from 'react';
import clickButton from "./click-button.mp3"
import pop from "./pop.mp3"
import useSound from 'use-sound';

const Checkbox = ({ name, checked, label, onChange}) => {
  return (
    <label style={{ display: 'flex', alignItems: 'center', fontSize: '16px', color: '#333', cursor: 'pointer' }}>
      <input
        type="checkbox"
        name={name}
        checked={checked}
        onChange={onChange}
        style={{ opacity: 0, cursor: 'pointer' }}
      />
      <span style={{ position: 'relative', width: '24px', height: '24px', border: '2px solid #333', marginRight: '10px' }}>
        {checked && (
          <span
            style={{
              content: '',
              position: 'absolute',
              top: '3px',
              left: '7px',
              width: '6px',
              height: '12px',
              border: 'solid #333',
              borderWidth: '0 3px 3px 0',
              transform: 'rotate(45deg)',
            }}
          ></span>
        )}
      </span>
      <span style={{ marginLeft: '5px' }}>{label}</span>
    </label>
  );
};

const SoundEffect = () => {
  const [isChecked, setIsChecked] = useState(false);
  const soundOptions = { volume: 0.5 };
  const [playOn] = useSound(clickButton, soundOptions);
  const [playOff] = useSound(pop, soundOptions);

  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
    isChecked ? playOff() : playOn();
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <Checkbox
        name="demo-checkbox"
        checked={isChecked}
        size={24}
        label="Checkbox"
        onChange={handleCheckboxChange}
      />
    </div>
  );
};

export default SoundEffect;
Playing Sound in React application

Code explanation

In the above App.js file:

  • Lines 1–4: Import necessary modules: React, useState for managing local state, the audio files clickButton.mp3 and pop.mp3, and the useSound Hook from the use-sound library. The useSound hook allows us to easily manage audio playback and is particularly useful for interactive elements like checkboxes, enhancing the user experience.

  • Lines 6–36: The custom Checkbox component is a functional component that renders a styled checkbox with a label and an animated checkmark, improving the overall design of the React application.

    • Line 14: The input checkbox is hidden by setting its opacity to 0, allowing for custom styling and ensuring a clean look. This technique helps maintain accessibility, as screen readers can still recognize the checkbox.

    • Lines 17–31: When checked is true, a checkmark appears inside the checkbox using a span element styled to resemble a checkmark. This rendering is conditional based on the checked prop.

    • This component accepts four props: name, checked, label, and onChange, which determine its functionality and appearance. This makes it versatile for various applications, allowing for easy integration and customization.

  • Lines 38–60: The SoundEffect component manages the checkbox’s checked state with the isChecked variable, toggled via the setIsChecked function. The useState Hook initializes isChecked to false, indicating the checkbox is initially unchecked.

    • Line 40: Configures the soundOptions, allowing us to set the audio volume for the sound effects at 0.5, which improves accessibility for all users by accommodating different sound preferences.

    • Lines 4–142: Uses the useSound Hook to create two functions, playOn and playOff, for playing sounds when the checkbox is checked or unchecked, respectively.

    • Lines 44–47: The handleCheckboxChange function toggles the checkbox state and plays the corresponding sound based on the checkbox status, enhancing user interaction. This function is crucial for both updating the UI and providing audio feedback, which improves the user experience.

    • Lines 50–58: The component’s main div centers the checkbox on the page using Flexbox for a clean layout, ensuring a visually appealing design. This approach helps maintain responsiveness and consistency across different screen sizes.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What does the useSound Hook return when provided with an audio file path?

A)

A function to manage checkbox states

B)

A function to play the sound

C)

A styled component for the checkbox

D)

A method to toggle audio playback

Question 1 of 30 attempted

Conclusion

Using the use-sound library to add sound feedback to checkboxes in React enhances both user experience and accessibility. This technique allows users to receive audio cues, making interactions more engaging and intuitive. We can expand this approach to include sound feedback for other UI elements like buttons, toggles, and more to create a richer, more immersive user experience. By integrating sound into the React applications, we not only improve functionality but also increase user satisfaction.

Note: Click here to learn more about sounds in React.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the use-sound library in React?

The use-sound library is a React Hook that simplifies the process of playing audio files in React applications, allowing developers to easily integrate sound effects for user interactions.


What are the benefits of using audio feedback in web applications?

Audio feedback enhances user engagement by providing immediate auditory responses to user actions, improving the overall user experience and accessibility.


Can I customize the audio volume in the use-sound library?

Yes, you can customize the audio volume in the use-sound library by passing a volume option when initializing the Hook. The volume value should be a number between 0.0 (muted) and 1.0 (full volume). Here’s an example:

import React from 'react';
import useSound from 'use-sound';
import soundEffect from './click-button.mp3';

const App = () => {
  // Initialize useSound with a volume level
  const [playSound] = useSound(soundEffect, { volume: 0.5 }); // 50% volume

  return (
    <button onClick={playSound}>
      Click me with sound
    </button>
  );
};

export default App;

In this example, we add a volume option inside the options object when calling useSound. This feature is useful for creating accessible and user-friendly applications where sound levels need to be controlled dynamically.


How do I manage checkbox state in React?

Checkbox state in React can be managed using the useState Hook, which allows you to create a state variable that tracks whether the checkbox is checked or unchecked.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved