Elad Weiss
Elad Weiss

Reputation: 4002

Uniting list of elements to one table row in react

I am very new to React.

I have a MonthEntry component containing a list of 1 or more instances of MonthPlanEntry. I want to display all the MonthPlanEntry in the list as a single table row.

class MonthPlanEntry extends React.Component {
    constructor(remaining_loan, interest, loan_reduce) {
        this.remaining_loan = remaining_loan;
        this.interest = interest;
        this.loan_reduce = loan_reduce;
    }
}

class MonthEntry extends React.Component {
    constructor(plans) {
        this.plans = plans;
    }

    render() {
        return (
            <tr>
                this.plans.map((plan, key) => {
                    <td>{plan.remaining_loan}</td>
                    <td>{plan.interest}</td>
                    <td>{plan.loan_reduce}</td>
                });
            </tr>
        );
    }
}

The problem is that every time I try to do something with the list I get an error: JSX expressions must have one parent element.ts(2657)

Edit:

To clarify - I want the MonthEntry to return a single <tr> composed of multiple MonthPlanEntrys. Each MonthPlanEntry will add 3 <td>s to the row.

Upvotes: 1

Views: 46

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Wrap the td tags with a React.Fragment and wrap the whole component inside a tr

    return (
        <tr>
            {this.plans.map((plan, key) => {
                <React.Fragment>
                   <td>{plan.remaining_loan}</td>
                   <td>{plan.interest}</td>
                   <td>{plan.loan_reduce}</td>
                </React.Fragment>
            });}
        </tr>
    );

Upvotes: 1

Related Questions