Alex Ironside
Alex Ironside

Reputation: 5059

Printing out values from a subarray to a table

I have an array looking like that:

var example = [
    {
        name: 'Alex',
        id: 1,
        jobs: [
            'potato picker',
            'spirit catcher',
            'pirate'
        ],
    },
    {
        name: 'Jonathan',
        id: 2,
        jobs: [
            'strawberry guard',
            'kings guard',
            'model'
        ],
    }
];

And I have a table in React looking like this:

<Table striped bordered condensed hover responsive>
    <thead>
    <tr>
        <th style={{textAlign: 'center'}}>Name</th>
        <th style={{textAlign: 'center'}}>ID</th>
        <th style={{textAlign: 'center'}}>Jobs<th>
    </tr>
    </thead>
    <tbody>
    {
        exampleArr.map((user, i) => (
            <tr key={user.id}>
                <React.Fragment>
                    <td>{user.name}</td>
                    <td>{user.id}</td>
                    {
                        user.jobs.map(job => (
                            <tr><td>{job}</td></tr>
                        {/*Obviously this throws an error*/}
                        ))
                    }
                </React.Fragment>
            </tr>
        ))
    }
    </tbody>
</Table>

This is more or less what I want end result to look like

enter image description here

How could I achieve said effect?

Putting the <tr> as a child of a <td> throws an error, obviously, but I think something like this is what I need.

I could in theory add the name and user id to each job element instead, but is there a way to do it in a simpler way?

Upvotes: 0

Views: 53

Answers (2)

imjared
imjared

Reputation: 20554

You can put your desired <tr>s in a subtable:

<tbody>
 {
     exampleArr.map((user, i) => (
         <tr key={user.id}>
             <React.Fragment>
                 <td>{user.name}</td>
                 <td>{user.id}</td>
                 <table>
                     {user.jobs.map(job => (
                         <tr>
                             <td>{job}</td>
                         </tr>
                     ))}
                 </table>
             </React.Fragment>
         </tr>
     ))
 }
 </tbody>

Upvotes: 1

Trenton Trama
Trenton Trama

Reputation: 4930

Do you really need new rows, or is it all right to have it contained within that one cell?

If you can have it in a single cell, wrap each job in a div, so it will display as a block.

user.jobs.map(job => (
    <div>{job}</div>
))

Upvotes: 1

Related Questions