Home > Net >  trying to use a condition inside map in react js
trying to use a condition inside map in react js

Time:10-29

I am trying to display data to the table from my database using api, but I want to limit the data to a certain number example if I get 10 table columns, I want to display only 5. Here is a peice of code for my map function:

import React, {useState} from 'react'
import { Icon, Table, Menu, Select, Form,Button } from 'semantic-ui-react'

const CustomerTable = (props) => {
    const{customer}=props;

  
    var leng=5;
    
    
    return(
 <div style={{marginTop:'15px'}}>
  <Table celled striped>
    <Table.Header>
      <Table.Row>
      <Table.HeaderCell>Name</Table.HeaderCell>
        <Table.HeaderCell>Address</Table.HeaderCell>
        <Table.HeaderCell>Actions</Table.HeaderCell>
        <Table.HeaderCell>Actions</Table.HeaderCell>
      </Table.Row>
    </Table.Header>
      
    <Table.Body > 
    {customer.map((c) => {
      return(
      <Table.Row key={c.id}>
        <Table.Cell>{c.name}</Table.Cell>
        <Table.Cell>{c.address}</Table.Cell>
         <Table.Cell>
            <Button color="red">Delete</Button>
         </Table.Cell>
         <Table.Cell>
            <Button color="red">Edit</Button>
        </Table.Cell>
      </Table.Row>

    )})}
            )

    </Table.Body>

  </Table>

 
</div>
    )
}

export default CustomerTable;

I tried if else condition (trying to get .length) but it doesnt work as I input the customer data as a prop from my other class. Thanks in advance for the help!!

CodePudding user response:

In case you now the condition before iterate you can slice the array.

<Table.Body > 

{/* You could slice the array */}
{customer.slice(0,5).map((c) => {
  return(
  <Table.Row key={c.id}>
    <Table.Cell>{c.name}</Table.Cell>
    <Table.Cell>{c.address}</Table.Cell>
     <Table.Cell>
        <Button color="red">Delete</Button>
     </Table.Cell>
     <Table.Cell>
        <Button color="red">Edit</Button>
    </Table.Cell>
  </Table.Row>

)})}
        )

</Table.Body>

In case you evaluate the condition while iterate through the array:

<Table.Body > 
{customer.map((c, index) => {
  if (index % 2 === 0) return null;

  return(
  <Table.Row key={c.id}>
    <Table.Cell>{c.name}</Table.Cell>
    <Table.Cell>{c.address}</Table.Cell>
     <Table.Cell>
        <Button color="red">Delete</Button>
     </Table.Cell>
     <Table.Cell>
        <Button color="red">Edit</Button>
    </Table.Cell>
  </Table.Row>

)}).filter(Boolean)}

{/* Filter the return array from map */}

        )

</Table.Body>
  • Related