Search code examples
javascriptreactjsdatatable

How can I displayed conditional data in the DataTable?


I am currently fetching the data using the axios get method and setting it in data variable using useState hooks in the json object. But I have one extra column in by DataTable which is the conditional on two parameter on json data.

Example:

If my json data is

{
        "name": "Xyz",
        "email_id": "cse@gmail.com",
        "check_out": null,
        "data": null,
        "check_in": null
    }

Then I had one column in DataTable with name Status whose work is to display present when check_in time is not null an Display absent when check_in time is null

I did this with ternary operator and the simple Table using bootstrap but i am confused how can we check the condition at the DataTable react library.

Here is my code for better understanding...

export default function Table() {

  const [data,setData]=useState([]);

  const columns = [
    {
        name: 'name',
        selector: row => row.name,
    },
    {
        name: 'email_id',
        selector: row => row.email_id,
    },
    {
      name:'Status',
      selector:row=>row.Status
    }
];


  useEffect(()=>{
    axios.get("view").then((response)=>{
      setData(response.data);
     
    }).catch((error)=>{
      console.log(error);
    })
  },[]);  
return (
    <DataTable
    columns={columns}
    data={data}/>
  )
}

Here is what i wanted (what i did using Bootstrap) enter image description here


Solution

  • You can do something like this.

    const data = [
      {
          "name": "Xyz",
          "email_id": "cse@gmail.com",
          "check_out": null,
          "data": null,
          "check_in": "test"
      },
      {
        "name": "abc",
        "email_id": "abc@gmail.com",
        "check_out": null,
        "data": null,
        "check_in": null
      },
    ];
    
    const columns = [
      {
        name: 'Name',
        selector: row => row.name,
      },
      {
        name: 'Email',
        selector: row => row.email_id,
      },
      {
        name:'Status',
        selector: row => row.check_in ? 'Present' : 'Absent'
      }
    ];