reactjs - Conditional rendering in JSX - Stack Overflow

I have an object that I want to render, 8 items per row. At every 8th item, I close the row div and sta

I have an object that I want to render, 8 items per row. At every 8th item, I close the row div and start a new row. This is my code

<div class="usage-row">
  {cpu.map((item, index) => (
  <>
    <div class="cpu">
      <i class={`bi bi-circle-fill ${item.description} led`}></i>
      CPU {item.realname}
    </div>
  {index % 8 === 7 && </div><div class="usage-row">}
  </>
  ))};
</div>

This fails on compilation and I cannot figure out why. Every div gets closed. Brackets and parenthesis checks out. Can anyone explain to me what's going on?

I have an object that I want to render, 8 items per row. At every 8th item, I close the row div and start a new row. This is my code

<div class="usage-row">
  {cpu.map((item, index) => (
  <>
    <div class="cpu">
      <i class={`bi bi-circle-fill ${item.description} led`}></i>
      CPU {item.realname}
    </div>
  {index % 8 === 7 && </div><div class="usage-row">}
  </>
  ))};
</div>

This fails on compilation and I cannot figure out why. Every div gets closed. Brackets and parenthesis checks out. Can anyone explain to me what's going on?

Share Improve this question asked Mar 6 at 9:16 Christian BrinchChristian Brinch 1097 bronze badges 2
  • 3 JSX doesn't work like a string concatenator, you need complete elements with opening/closing tags. If you want to create multiple usage-rows put the map outside of that element. – DBS Commented Mar 6 at 9:19
  • 2 You're treating jsx like php literal, JSX must be enclosed. You need to split your cpu array into chunks and use each chunk to generate each usage-row – Hao Wu Commented Mar 6 at 9:27
Add a comment  | 

1 Answer 1

Reset to default 1

Like @DBS said, with JSX, you should be creating and returning whole elements, so you're looking for something like this:

const cpuRows = /* CPUs split into groups of 8 */

return <>
  {cpuRows.map((row, i) => (
    <div key={i} className="usage-row">
      {row.map((item, j) => (
        <div key={item.id /* or j if the cpu doesn't have a unique key */} className="cpu">
          <i className={`bi bi-circle-fill ${item.description} led`}></i>
          CPU {item.realname}
        </div>
      ))}
    </div>
  ))}
</>

Note that each element returned by a map call should have a unique key property React will use internally. Also, some common attributes are reserved keywords and have different names in JSX, i.e. className instead of class.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744987087a4604675.html

相关推荐

  • reactjs - Conditional rendering in JSX - Stack Overflow

    I have an object that I want to render, 8 items per row. At every 8th item, I close the row div and sta

    20小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信