Muzamil Hussain
Muzamil Hussain

Reputation: 33

How to write if condition in table tags using ReactJS

if condition is not working in ReactJS. I want to create an Accordion and fetch data from excel sheets. And set ID's which data is displayed which button and I am unable to create if conditions.

{items.map((d) => (
        <Accordion key={d.ID} 
          title={
            <div>
              <tr className="btn-heading">
                <td>{d.ID}</td>
                <td>{d.Mail}</td>
                <td>{d.Name}</td>
                <td>{d.PhoneNo}</td>
                <td>{d.City}</td>
                <td>{d.Date}</td>
                <td>{d.Time}</td>
              </tr>
            </div>
          }
          content={
            <div>
              <p className="header">
                  <span className="header-content">Shipping Address:</span>
                  292 Naqshband Colony. Near rabbania Mosque. Multan
              </p>
              <Table size="sm">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Article No</th>
                    <th>Product Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total Amount</th>
                  </tr>
                </thead>
                <tbody>
                  {products.map((c) =>
                  (
                    if(c.ID === 1) {   <--- this if condition is not working      
                      <tr key={c.ID}>
                        <td>{c.ArticleNo}</td>
                        <td>{c.ProductName}</td>
                        <td>{c.Quantity}</td>
                        <td>{c.Price}</td>
                        <td>{c.TotalAmount}</td>
                      </tr> 
                    }                                        
                  ))};
                </tbody>
              </Table>

Here is my codesandbox: https://codesandbox.io/s/hungry-bardeen-8m2gh?file=/src/App.js

Upvotes: 0

Views: 5350

Answers (1)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You could use ternary operator for checking if-else statement.

Modify the part of code as follows,

Change,

{products.map((c) =>
   (
    if(c.ID === 1) {   <--- this if condition is not working      
    <tr key={c.ID}>
     <td>{c.ArticleNo}</td>
     <td>{c.ProductName}</td>
     <td>{c.Quantity}</td>
     <td>{c.Price}</td>
     <td>{c.TotalAmount}</td>
    </tr> 
   }                                        
))};

To:

   {products.map((c) =>
     c.ID === 1 ? (
     <tr key={c.ID}>
      <td>{c.ArticleNo}</td>
      <td>{c.ProductName}</td>
      <td>{c.Quantity}</td>
      <td>{c.Price}</td>
      <td>{c.TotalAmount}</td>
    </tr>
    ) : null
   )}

Forked Sandbox:

Edit romantic-shannon-10gme

Upvotes: 1

Related Questions