whitebear
whitebear

Reputation: 12457

Dynamically made strings for id in JSX

I want to make id like this dynamically.

<div id="track_1"></div>
<div id="track_2"></div>

So I gave the id like this from parent component.

export default function Components(props) {
  return (
      <AudioTrack trackNum="1"/>
      <AudioTrack trackNum="2"/>
  )
}

then in my AudioTrack Component I got the trackNum and want to use like this

const AudioTrack = (props) => {
  return(  
    <div id="track_{props.trackNum}" ></div>
  );
}

Howeber it doesn't work.

Is there any good way?

Upvotes: 0

Views: 43

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371118

Since the div prop isn't a constant string, you need {} to indicate an expression, and then either use + to concatenate or a template literal with ${}:

<div id={`track_${props.trackNum}`}></div>

Upvotes: 2

Related Questions