Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using map() to iterarate an array of objects to render them on my app. I have imported audio files and I would like to reference them for the src attribute when mapping. src={x.sound} evaluates to just text, as it should. How can I achieve something like this src={{x.sound}} => src={boom} so that the srcwould actually be a valid path after iteratively rendering?

Thank you!

import boom from "./sound/boom.ogg";

const data = [
  {
    key: "Q",
    keyCode: 81,
    sound: "boom",
  },
];

const buttons = () =>
  data.map((x) => (
    <div
      onClick={this.clickHandle}
      id={x.sound}
      className="drum-pad"
      key={x.key}
    >
      {x.key}
      <audio
        id={x.key}
        key={x.key}
        src={x.sound}
        className="clip"
        controls
      ></audio>
    </div>
  ));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
308 views
Welcome To Ask or Share your Answers For Others

1 Answer

In your example, you are passing string ('boom') to the audio tag's source property. For JS/React it is not implied to look up if the current scope's variables contain one named after a particular string.

There are 2 ways you could make this work.

  1. You can change your data object's sound property to reference the imported sound object (instead of string)
import boom from './sound/boom.ogg';

const data = [
  {
    key: 'Q',
    keyCode: 81,
    sound: boom,
  },
];
  1. If you are serving your static files in 'public' folder on the server, you could put your audio file there as well. And then get it using a relative path.
const data = [
  {
    key: 'Q',
    keyCode: 81,
    sound: './boom.ogg',
  },
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...