Home > database >  how to show image and audio on React.js (in a Stupid Simple way)
how to show image and audio on React.js (in a Stupid Simple way)

Time:10-05

I had a flashdrive with songs and photos stick on my router, shared on my wifi, and a simple html file I made to display it like a page. Now I'm trying to make it in react.js

On html I only needed to

<audio controls> 
  <source src="the path" type="audio/mpeg">
</audio>

and for the image it was also very simple but on react I can't find a single tutorial on how to do it and all awnsers on the matter involve props, imports, github projects installs and the like. What is the most 'keep it simple stupid' way to display an image or mp3 file with JSX? localhost3000 just show image as broken, even with the files on the very same computer.

CodePudding user response:

It's very easy to achieve, you're almost there. The following code works (you forgot to close the source tag)

 <audio controls> 
    <source src={audio} type="audio/mpeg"/>
  </audio>

You'll have to import your audio file also before passing it into src. This is my import:

import audio from 'assets/audio/song.mp3'

For me, song.mp3 was stored in my assets directory. I imported it as audio which is a completely arbitrary name, it could be whatever you want as long as you make sure to pass the same name to src.

Edit: the src attribute can also take a url. So this will work too:

 <audio controls> 
        <source src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg"/>
      </audio>

CodePudding user response:

for to add image the first time is import the image like this

import logo from './logo.png'; // path location of image file in same folder project

after that you can put the image with this code

<img src={logo} alt="Logo" />
  • Related