Search code examples
reactjsloopsconditional-rendering

React Nested Loops and Keys


I'm trying to get a bit of react code to work and am struggling with conditional rendering. The following:

      <div id="table_holder" className="table-responsive mx-3">
        <table className="table-sm">
          {Tables.map((tableRows, index) => (
            <thead key={'headeer'+index.toString()}><tr key={index.toString()}>
            {tableRows.map((tableRow, i) => (
              <th key={i.toString()}>
                {i}
              </th>
            ))}
            </tr></thead>
          ))}
        </table>
      </div>
      );

works but I'd like to conditionally display different table cells depending on the the value of the key 'type' in the object tableRow. And can't seem to manage the right syntax

Thanks


Solution

  • Your first loop is not assigning a unique key to the div. That might be the problem. Try to give key like this.

    <key={index}>

     <table className="table-sm">
              {Tables.map((tableRows, index) => (
                <key={index}>
                {tableRows.map((tableRow, i) => (
                  <th key={i+index.toString()}>
                    {i}
                  </th>
                ))}
                </>
              ))}
            </table>
    

    UPDATE 2

    This is how you can use conditional rendering in react.

      var tableRow = [1, 2, 4, 6, 7];
      return (
        <div className="App">
          <h1>Your React App</h1>
          {tableRow.map((table, index) => {
            if (table % 2) {
              return <div key={index}>{table}</div>;
            }
          })}
        </div>
      );