Search code examples
reactjsreact-nativejsxflatlist

Conditionally add attributes to components


I have a flatlist where i want to add columnWrapperStyle only if numColumns greater than 1 , else I am getting some error.I tried something like below

     <FlatList
              data={data}
              if(numColumns>1)
              {
                columnWrapperStyle={{ justifyContent: "space-evenly" }}
              }
            }
>

I searched and many telling to use states inside attribute..but i do not want attribute name itself.how do i do it ?


Solution

  • Method 1

    Creating the props outside:

    const flatlistProps = numColumns > 1 ? { data, columnWrapperStyle : ...} : { data }
    
    <Flatlist {...flatlistProps} />
    

    Method 2

    Conditional rendering:

    {numCounts > 1 ? <Flatlist data={data} columnWrapperStyle={...} /> : <Flatlist data = {data} />}