How to write dynamically in Javascript (react project)

Viewed 51

I had a static code that was working just fine, but when I tried to use a map() over a array to produce the same result dynamically, it doesn't work anymore.

I think that I made a syntax mistake when mapping my array. Can someone point out what is my mistake?

Here is the old static code that works fine:

const GridContent = (props)=>{
    return (
        <div className={classes.Container}>
           <ProgressBar percentage="100" styleName="ProgressBar1"></ProgressBar>
           <ProgressBar percentage="24" styleName="ProgressBar2"></ProgressBar>
           <ProgressBar percentage="48" styleName="ProgressBar3"></ProgressBar>
        </div>
    );
}

Here is what I tried to make it dynamic:

const fakeData3=[{percentageItem: '100'}, {percentageItem: '24'}, {percentageItem: '48'}, {percentageItem: '12'}, {percentageItem: '90'}, {percentageItem: '57'}, {percentageItem: '72'}, {percentageItem: '50'}, {percentageItem: '39'}]

const GridContent = (props)=>{
    return (
        <div className={classes.Container}>
            {fakeData3.map((item, index)=>{
                return <ProgressBar percentage={`"${item.percentageItem}"`} styleName={`"ProgressBar${index+1}"`}></ProgressBar>
            })}
        </div>
    );
}

I think there is a syntax mistake on the return of my last part of code ...

3 Answers

I think you have overcomplicated your quotes here -

<ProgressBar percentage={`"${item.percentageItem}"`} styleName={`"ProgressBar${index+1}"`}></ProgressBar>

try -

<ProgressBar percentage={item.percentageItem} styleName={`ProgressBar${index+1}`}></ProgressBar>

You're mixing quotations. The right code should be:

return <ProgressBar percentage={item.percentageItem} styleName={`ProgressBar${index+1}`} />
  1. percentage is already a string, so you can use it directly as {item.percentageItem}

  2. If you do `"something"`, styleName is actually becoming "\"something\"" (notice the escaped ") internally.

You have to remove the redoundant double quotes:

{fakeData3.map((item, index) => (
    <ProgressBar percentage={item.percentageItem} styleName={`ProgressBar${index+1}`} />
))}
Related