1

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?

4
  • 1
    You can't leave the element open like that, JSX needs elements with closed tags. Commented Jan 2, 2018 at 16:52
  • @MinusFour but everything is being closed, are you refering to the <tr> tag? Commented Jan 2, 2018 at 16:56
  • the return in the if statement exits the map call. The code you wrote just doesn't make much sense. If you re-create this on codesandbox.io then it will be easy for us to help. Commented Jan 2, 2018 at 16:56
  • @gabrriel_bu exactly, you are leaving the tr tag open Commented Jan 2, 2018 at 16:58

1 Answer 1

5

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>
   );
Sign up to request clarification or add additional context in comments.

1 Comment

You should also take a look at [If-Else in JSX[(react-cn.github.io/react/tips/if-else-in-JSX.html). It will explain why you cannot use if else inside JSX. The short is: if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.