Thursday, 17 June 2021

How to handle condition rendering in react

I am using react-grid-layout This to enable drag and drop and resizing in my website. SO drag and drop I am able to achieve and storing my layout to local storage is also done.

I am using Local storage to save my layout for better user experience using This example

the thing is what I am trying to do is conditionally give height and width to boxes, like if empName==="steve" than width should be 5 or else it should be 3

So what I did is

const generateLayout = () => {
  const p = data1 || []; //props;
  return p[0].comp_data.map(function (item, i) {
    console.log(item);
    if (item.empName === "steve") {
      return {
        x: (i * 2) % 12,
        y: Math.floor(i / 6),
        w: 2,
        h: 4,
        i: i.toString()
      };
    } else {
      return {
        x: (i * 2) % 12,
        y: Math.floor(i / 6),
        w: 4,
        h: 2,
        i: i.toString()
      };
    }
  });
};

The above approach does not work as required.

Here is the full working code

Edit update

I changed my data, as it was wrong I was looping through p[0]

Now what I did is I created one data for tabs That will show menu ie

    let tabData = [
    {
        tab: 'info',
        id: 1,
    },
    {
        tab: 'info1',
        id: 2,
    },
];

and the other one I have is compData that will have emp status

LIke below

    let data1 = [
    {
        comp_data: [
            {
                empId: 1,
                empName: 'el1',
            },
            {
                empId: 2,
                empName: 'el2',
            },
        ],
    },
    {
        comp_data: [
            {
                empId: 11,
                empName: 'el11',
            },
            {
                empId: 12,
                empName: 'el22',
            },
        ],
    },
];

Important -- actually in my real scenario I am getting all the tabs at one go than I click on one tab get id of that and get compData for that id from backend but here I cannot do it so I put in data1 two objects one for first company and other for other company.

I think this the way for write explanation here

updated code sandbox please check



from How to handle condition rendering in react

No comments:

Post a Comment