gabrriel_bu
gabrriel_bu

Reputation: 67

React / Javascript If statement inside map

I'm trying to make a table which will have different coloured rows depending on an attribute which is derived from a map function:

       var tableData = this.state.data.map(attribute =>

            {if(attribute.duplicate.toString()== "true")
                return <tr className="table-success">;
            else
                return <tr className="table-warning">;
            }
                <td> {count++} </td>
                ...
                <td> {attribute.duplicate.toString()} </td>
            </tr>
       );

Now var tableData gets passed through to the actual table:

<div>
        <div>
            <table className="table">
                <tr className="thead-inverse">
                    <th> # </th>
                    ...
                    <th> duplicate </th>
                </tr>
                    {tableData}
            </table>

        </div>
    </div>

But I get the following error:

[INFO] Module build failed: SyntaxError: C:/Users/.../all.js: Unterminated JSX contents (78:14)
[INFO] 
[INFO]   76 | 
[INFO]   77 |             </div>
[INFO] > 78 |         </div>
[INFO]      |               ^

Any ideas what the problem is, or another way to achieve what I'm trying to do?

Upvotes: 1

Views: 1441

Answers (1)

MinusFour
MinusFour

Reputation: 14423

Just move the conditional logic inside the className or assign it to a variable and then use it inside the tr.

   var tableData = this.state.data.map(attribute => 
       <tr className={attribute.duplicate.toString() == "true" ? "table-success" : "table-warning"}>
            <td> {count++} </td>
            ...
            <td> {attribute.duplicate.toString()} </td>
        </tr>
   );

Upvotes: 5

Related Questions