-1

I'm rendering a table based on map (data) of maps (column headers). I am unable to add an if condition before item[col.property] as it returns an unexpected value error.

How would I conditionally render an <a href> with the returned item[col.property] value as the href value if the col.heading is equal to 'specifiedHeader'.

I assume the if conditional logic would be, but I'm getting the placement wrong:

{if (col.heading == 'specifiedHeader') {
   <td><a href={item[col.property]}/></td>
   }
else {
   <td>{item[col.property]}</td>
   }
}

const Table:

  const Table = ({ columns, data }) => (
    <table className="table">
      <thead>
        <tr>
          {columns.map(col => (
            <th key={`header-${col.heading}`}>{col.heading}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map(item => (
          <tr>
            {
              columns.map(
                col => (
                  <td>
                    {
                      item[col.property]
                    }
                  </td>
                ))
            }
          </tr>
        ))}
      </tbody>
    </table>
  );
S.B.
  • 437
  • 2
  • 6
  • 19

3 Answers3

2

You can use a ternary operator: https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

{
    col.heading === 'specifiedHeader' ? (
        <td><a href={item[col.property]}/></td> 
    ) : (
        <td>{item[col.property]}</td>
    )
}
wxker
  • 1,841
  • 1
  • 6
  • 16
1

Try this:

{col.heading === 'specifiedHeader' &&
  <td><a href={item[col.property]}/></td>
}{ col.heading !== 'specifiedHeader' &&
   <td>{item[col.property]}</td>
}
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
0

Replace your second columns.map with this:

columns.map(
  col => (
    <td>
      {
        col.heading === 'specifiedHeader'
          ? item[col.property]
          : <a href={item[col.property]}/>
      }
    </td>
  ))
huytc
  • 1,074
  • 7
  • 20