Home > front end >  Using Variable inside jsx loop
Using Variable inside jsx loop

Time:04-11

I have loop like this inside jsx render

return(
<View>
   {[...Array(10)].map((x, i) => (
          <Input
            placeholder="Category {i}"
          />
        ))}
</View>
)

I am trying to create 10 inputs dynamically using above code , here I want to use the variable I inside place holder so I get the inputs with placeholder Category 1 , Category 2 etc., but my app is crashing without any error , what is the proper way to use variable inside the map of jsx.

CodePudding user response:

You can use a javascript variable in a string wrapped by template char: "'".

And you need to set key in children.

return(
<View>
   {new Array(10).map((x, i) => (
          <Input
            key={i}
            placeholder={`Category ${i}`}
          />
        ))}
</View>
)

CodePudding user response:

Maybe try this

return (
  <View>
    {new Array(10).map((x, i) => (
      <Input placeholder={`Category ${i   1}`} />
    ))}
  </View>
);

Refer to this

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

CodePudding user response:

For any one wondering , I solved it by writing code like below.

  {[...Array(10)].map((x, i) => {
          return (
            <Input        
              placeholder={"Category "   (i   1)}
            />
          );
        })}
  • Related