'React-Native toggle between grid and list views

I want to implement a button that switches my list view to grid from list and vice-versa. And my Items are Cards with images and info below them What is the best way to implement this ?

Should I have two flatLists one for grid and one for list with different settings. Or is there a better way to handle this like an already existing component ?



Solution 1:[1]

You have to create two different flatList and than call a boolean to switch from one to an other:

Enum DisplayType {
  grid,
  list
}

const yourComponent = () => {

  const [displayType, setDisplayType] = useState<DisplayType>(DisplayType.grid);

  return (
    <>
      {displayType === DisplayType.grid ? <MyFlatListInGrid /> : <MyFlatListInList />}
    </>
  )

}

I have experienced other way to do this but this is the best by far and the less "laggy" one.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lmasneri