简体   繁体   中英

JSX conditional element in loop

How to define opening of a tag on a condition and closing of tag on another. In the below sample I'm trying to wrap every two element on a new row. However doesn't seem to work. Sample - https://jsfiddle.net/reactjs/69z2wepo/

render() {
    let menuItems = [];
    for (var i = 0; i < 10; i++) {
        menuItems.push(
        {i%2 !== 0 ? <div class="row">:<>}
        <div>hi</div>
        {i%2 === 0 ? </div>:<>}
        );
    }
    return <div>{menuItems}</div>;
  }

Build your data objects before rendering; this allows React to render in a declarative manner, and is flexible enough to render as many rows or columns that you'd like to add.

Also, I left the creation of the rows array purposely verbose; there's no reason you can't have a numRows variable that's used in a loop to append to the rows array.

https://codesandbox.io/s/clever-moser-3j51c

Component

function App() {
  const cell = "hi";
  const rows = [
    [cell, cell],
    [cell, cell],
    [cell, cell],
    [cell, cell],
    [cell, cell]
  ];

  return rows.map((row, i) => {
    return (
      <div key={i} className="row">
        {row.map((data, j) => (
          <span key={j}>{data}</span>
        ))}
      </div>
    );
  });
}

Output

hi hi
hi hi
hi hi
hi hi
hi hi

Since you didn't provide CSS, I swapped your inner <div> elements for <span> , so it up to you to style this appropriately.

You need to revert your logic. You are trying to always insert a <div> but what you need to do is keep it in an array the <div> and push it only in the desired time.

render() {
    let menuItems = [];
    let hiDivs = []
    for (var i = 0; i < 10; i++) {
        hiDivs.push(<div>hi</div>)
        if(hiDivs.length === 2){
            menuItems.push(<div class="row">{hiDivs}</div>)
            hiDivs = []
        }
    }
    return <div>{menuItems}</div>;
}

You can use dangerouslySetInnerHTML but it's very very bad and not recommended...

How about doing it this way?

  render() {
      let menuItems = [];
      for (var i = 0; i < 10; i++) {
          const hi = <div>hi</div>
          const item = i%2 === 0
              ? <div className="row">{hi}{hi}</div>
              : hi;
          menuItems.push(item);
      }
      return <div>{menuItems}</div>;
  }

You might want to add a 'key' attribute as well since react will throw a warning otherwise for arrays of elements.

If your desired output is simply what is below with no other constraints (ie always two hi s inside each row)

<div className="row">
   <div>hi</div>
   <div>hi</div>
</div> 
<div className="row">
   <div>hi</div>
   <div>hi</div>
</div>
..........

You can do:

let menuItems = []
for(let i = 0 ; i < 5; i++){
  menuItems.push(<div className="row"><div>hi</div><div>hi<div></div>)
}

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