Reputation: 91
I have a problem with generated dynamic path to import file in React. I used map() function for generated dynamic part of code, which is a sequence of the same few div elements with an audio element inside this div. This code looks like this:
{soundsName.map((sound, i) => {
return (
<div
className="drum-pad"
onClick={this.soundPlay}
title={"Sound " + sound}
key={i}
>
<audio className="clip" id={sound}>
<source src={`s${i}`} type="audio/mpeg"></source>
</audio>
{sound}
</div>
);
})}
My problem is that the generated path in 'src' for 'source' element is wrong. The path is only the name of imported file, like 's1', 's2', 's3' and so on.
Files are imported like this:
import s0 from "./assets/sounds/s1.mp3";
import s1 from "./assets/sounds/s2.mp3";
import s2 from "./assets/sounds/s3.mp3";
import s3 from "./assets/sounds/s4.mp3";
import s4 from "./assets/sounds/s5.mp3";
import s5 from "./assets/sounds/s6.mp3";
import s6 from "./assets/sounds/s7.mp3";
import s7 from "./assets/sounds/s8.mp3";
import s8 from "./assets/sounds/s9.mp3";
I really don't know, what I am doing wrong :( Maybe some of you know that?
Thanks for any help.
Upvotes: 0
Views: 976
Reputation: 5079
You should put the source as ./assets/sounds/s${i}.mp3
instead of s${i}
and you will get the following src="./assets/sounds/s1.mp3"
EDIT for your specific case:
Put all the components into an array for example:
let soundPaths = [s1, s2, s3, s4 /*... and rest of components */]
Then in your map()
function do
<source src={soundPaths[i]} type="audio/mpeg"></source>
Upvotes: 2
Reputation: 110
import s0 from "./assets/sounds/s1.mp3";
import s1 from "./assets/sounds/s2.mp3";
import s2 from "./assets/sounds/s3.mp3";
import s3 from "./assets/sounds/s4.mp3";
import s4 from "./assets/sounds/s5.mp3";
import s5 from "./assets/sounds/s6.mp3";
import s6 from "./assets/sounds/s7.mp3";
import s7 from "./assets/sounds/s8.mp3";
import s8 from "./assets/sounds/s9.mp3";
sound=[
{
sound_name:"s1"
path:s1
},
{
sound_name:"s2"
path:s2
}, {
sound_name:"s3"
path:s3
}, {
sound_name:"s4"
path:s4
}, {
sound_name:"s5"
path:s5
}, {
sound_name:"s6"
path:s6
}, {
sound_name:"s7"
path:s7
}, {
sound_name:"s8"
path:s8
},
]
this is a way
{soundsName.map((sound, i) => {
return (
<div
className="drum-pad"
onClick={this.soundPlay}
title={"Sound " + sound.sound_name}
key={i}
>
<audio className="clip" id={sound.sound_name}>
<source src=sound.path type="audio/mpeg"></source>
</audio>
{sound.sound_name}
</div>
);
})}
Upvotes: 0