Ketan Malhotra
Ketan Malhotra

Reputation: 1250

react native - Having static and dynamic elements in FlatList

I'm trying to create a FlatList somewhat like Twitter's Post Tweet list displaying options ranging from Camera to Photos in the Gallery of the device.

enter image description here

I'm not sure how to have first 2-3 elements as static elements and then add on dynamic elements via a CameraRoll or something.

The first solution that came to my mind was having an array with its first 2-3 elements as text containing "Camera", "Gallery" etc. and then concatenate that array with the dynamic array and handle everything via the renderItem() function to display different view for the "static element" case. But I'm hoping that there's a better way to do this. Please help me out with this.

Upvotes: 4

Views: 4807

Answers (2)

TomRavn
TomRavn

Reputation: 1244

It can be done using ListHeaderComponent prop inside FlatList. We can put there any JSX and achieve static first item.

   <FlatList
      data={data}
      renderItem={({item, index})=><Item musicItem={item} index={index} currentIndex={currlistIndex} db_index={item.id_db}/>}
      extraData={currlistIndex}
      ListHeaderComponent={<AddSongs/>}             
    /> 

Upvotes: 0

Tholle
Tholle

Reputation: 112807

I think the best and easiest option is to do it the way you outlined: Concatenate the "static" array with the "dynamic" array, and treat the static ones separately.

Example

class Options extends React.Component {
  renderItem({ item, index }) {
    if (index === 0) {
      return <Camera />;
    } else if (index === 1) {
      return <Live />;
    } else {
      return <GeneralItem {...item} />;
    }
  }

  render() {
    const statics = [{ text: 'Camera' }, { text: 'Live' }];

    return (
      <FlatList
        data={statics.concat(this.props.data)}
        renderItem={this.renderItem}
      />
    );
  }
}

Upvotes: 5

Related Questions