Search code examples
javascriptreactjshtml-tableconditional-rendering

React - Extra table row printing incorrectly


I am looping through an array of objects, then based on a condition I am display that row in one Table or the other. However, when i call that condition, the object reacts how I would like (it displays in Table1) but in Table2 a number is being printed out also. The following is a snippit example. files contains and array of objects, person. If the person is male, they are added to an array and that array is passed to a seperate componenet and rendered elsewhere, This works. If the person is not male, they are returned in the table underneath the condiditon.

<tbody>
{props.files.map(person=> ( 
    <div>
        {(person.gender === "male") ? maleArray.push(person) :
            <tr>
                <td>{person.name}</td>
                <td>{person.age}</td>
            </tr>
         }
    </div>
))}
</tbody>

The problem is, everytime a male is detected, they are not displayed in the female table but a number is printed instead. For example,

Name Age
Mary 51
1
Jane 19

The male table works as expected but if a male is detected in the loop, i get this output in the female table.

EDIT: Table is printing weird in final version. It would look something like this
Name Age
Mary 51
1
Jane 19


Solution

  • In JSX you use ternary operator, it ALWAYS returns value when execution is finished, and that returned value is passed to a markup. So when a loop executes on "female" table, along with female names it shows the result of execution push method on an array in place of male names, which is an array length, that's why you see integers in a table. Try to separate male and female names in a component, not in JSX, and then there is no need to put a condition in JSX