Report this

What is the reason for this report?

How to set a background music in React without any player.

Posted on December 18, 2020

I just want to add background music that will play continuously. Everything, I got is a player and I need to click the play button or any button. That’s what I don’t want. In HTML is easy. But how about React.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya,

Just came across this answer and decided to write some general guidelines for anyone who comes across this in the future despite the old question.

Adding continuous background music to a React app can be achieved using the HTML5 <audio> tag in combination with React state and lifecycle methods to control playback. Using the ‘autoPlay’ attribute will allow the audio to start once the component has mounted.

  1. import React from 'react';
  2. class MusicPlayer extends React.Component {
  3. render() {
  4. return (
  5. );
  6. }
  7. }

Note: Autoplaying sound can provide a poor user experience, and many browsers have settings to limit or disable autoplaying. Mobile browsers generally do not allow autoplaying sound at all. Therefore, it’s best to give your users control over sound on your site.

For more information on how to use these tags and attributes in a more advanced way, you can follow React’s guide on uncontrolled components

Hope that this helps!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.