Search code examples
reactjsjsxstring-interpolation

JSX/React interpolation/syntax


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>
  ));

Solution

  • 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',
      },
    ];