skip to Main Content

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


  1. The error status is not defined, might occur if some of the objects in the paymentstate do not have the status property. To avoid this error, you can add an additional check to ensure that the status property exists before using:

    .....
    let statusClassName = "badge"; //set as default class
    
    if (value.hasOwnProperty("status")) {
      if (value.status === "pending") {
        statusClassName += " badge-warning";
      } else if (value.status === "success") {
        statusClassName += " badge-success";
      } else if (value.status === "cancel") {
        statusClassName += " badge-danger";
      }
    }
    .....
    
    Login or Signup to reply.
  2. 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

    const STATUS_BADGET_COLOR = {
    pending: 'badge badge-warning',
    success: 'badge badge-success',
    cancel: 'badge badge-danger'
    }
    

    and use it in your template className={STATUS_BADGET_COLOR[value.status]}

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search