Hacktoberfest – Adding sound and images to a React app

Hey everyone,

It seems like allot of people like to over complicate adding sound and images in React.  They will often make a whole separate class to control their sound or image files. Which definitely has its place, if your sound or images needs bunch of options then definitely make a class to control it. But if all you want to do is play a sound or add a image to your app, I think its simpler to add it in directly inside the class it relates to.

Note:  I also learned that React doesn’t like when you refer to something by its path inside the code. You have to use a import statement in order to include a file into your react app. In the code below you will see me do this.

 

Playing Sound in React:

Below is how I figured out how to play sound from my react app in just a few statements.

import mp3_file from './yourFileName.mp3';

playSound(){
   this.Sound.play();
}

<audio src={mp3_file} ref={Sound => { this.Sound = Sound; }}/>
Adding a Image in React:

Below is a simple way of adding a image to your React app.

import myImg from './yourFileName.png';

<img src="{myImg}" />