简体   繁体   中英

React: render each component in array

In my application, I want the React MUI library component, AccordionDetails to display each element in array targetTypeData (the length of the array is currently always 6). The array contains a Typography component.

My current solution properly displays the data has limitations and is not concise. Is there another way to render each element in an array?

  var targetTypeData = [];
          for(let i=0; i<targetTypes.length;i++){
            targetTypeData.push(
              <Typography sx={{ fontSize: 14 }} 
              color= {"white" } >
              {`${targetTypes[i].toString()} : ${targetNumberData[i].toString()}`}
            </Typography> 
            )
          }

   //more code
          <AccordionDetails>
              <Typography>
                {targetTypeData[0]}
                {targetTypeData[1]}
                {targetTypeData[2]}
                {targetTypeData[3]}
                {targetTypeData[4]}
                {targetTypeData[5]}

              </Typography>

            
        </AccordionDetails>

(Edited) Try this:

      var targetTypeData = [];
      for(let i=0; i<targetTypes.length;i++){
        targetTypeData.push(
          `${targetTypes[i].toString()} : ${targetNumberData[i].toString()}` 
        )
      }
      // more code
      <AccordionDetails>
            {targetTypeData.map((item) => (
               <Typography sx={{ fontSize: 14 }} color= {"white"} >
                   {item}
               </Typography> 
            ))}
      </AccordionDetails>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM