Alexandre Paiva
Alexandre Paiva

Reputation: 1523

How to display a component stored in a variable in React

I have a block of code where I need to display a badge when the passport is due to expire, otherwise no badge should be displayed:

const displayMonths = (passport_date) => {

    const months = moment().diff(passport_date, 'months') * (-1)

    if (months > 0 && months <= 12) {

        return <span class="badge badge-warning"> months remaining</span>
    }
    else if (months <= 0) {

        return <span class="badge badge-danger"> months expired</span>
    }
    else {

        return ""
    }
}

return (
    <>
        {`${moment(row.passport_date).format('DD/MM/YYYY')} ${displayMonths(row.passport_date)}`}
    </>
)

The problem is that inside of the return the displayMonths is displaying the object (Eg: 01/04/2018 [object Object]) and I cannot display the related HTML instead. How to achieve this? Thanks

Upvotes: 0

Views: 369

Answers (1)

Panther
Panther

Reputation: 9408

You return should be like below. Because you are returning a jsx. Putting that into a `` would try to convert it to a string and hence [object object]. The below way would render the jsx directly.

return (
 <>
   {moment(row.passport_date).format('DD/MM/YYYY')}
   {displayMonths(row.passport_date)}
 </>
);

Upvotes: 1

Related Questions