I am using react and using map function . I want to use conditionally change class when my payment status will change I use if else statement but its give that status is not define .
<table className="table display expandable-table">
<thead>
<tr>
<th>S.no</th>
<th>Name</th>
{/* <th>Transaction no.</th> */}
<th>Amount</th>
<th>Mode of payment</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{paymentstate.map((value, key) => {
let statusClassName;
if (value.status === "pending") {
statusClassName = "badge badge-warning";
} else if (value.status === "success") {
statusClassName = "badge badge-success";
} else if (value.status === "cancel") {
statusClassName = "badge badge-danger";
}
return (
<tr key={key}>
<td>{key + 1}</td>
<td>{value.name}</td>
{/* <td>9879278397823</td> */}
<td className="font-weight-bold">₹{value.amount}</td>
<td>{value.payment_mode}</td>
<td>21 Sep 2018</td>
<td className="font-weight-medium">
<div className={statusClassName}>Completed {value.status}</div>
</td>
</tr>
);
})}
</tbody>
</table>
2
Answers
The error status is not defined, might occur if some of the objects in the
paymentstate
do not have thestatus
property. To avoid this error, you can add an additional check to ensure that thestatus
property exists before using:During the initial render, the items list may be an empty array or some items in the list may not have the status property defined.
Alternative, you can create an object like this in your component
and use it in your template
className={STATUS_BADGET_COLOR[value.status]}
Demo