skip to Main Content

App.js

import React from 'react';
import {
  SafeAreaView,
  View,
  FlatList,
  StyleSheet,
  Text,
  StatusBar,
} from 'react-native';

const DATA = [
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
];

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);
const Render_FlatList_Sticky_header = () => {
  return (
    <>
      <Text>hello</Text>
    </>
  );
};
const App = () => {
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={({ item }) => <Item title={item.title} />}
        keyExtractor={(item) => item.id}
        stickyHeaderIndices={[0]}
        ListHeaderComponent={Render_FlatList_Sticky_header}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

export default App;

it’s working with a sticky Header but I want different header when item.id is different

like

  • if Item.id=1 then my sticky Header text is "A",

  • if Item.id=2 then my sticky Header text is "B",

  • if Item.id=3 then my sticky Header text is "B"

I try to do that but it gives me an error

anyone can help me??🐼

3

Answers


  1. You can do something like this:

    import React from "react";
    import {
      SafeAreaView,
      View,
      FlatList,
      StyleSheet,
      Text,
      StatusBar,
    } from "react-native";
    
    const DATA = [
      {
        id: "0",
        title: "Zero Item",
      },
      {
        id: "1",
        title: "First Item",
      },
      {
        id: "2",
        title: "second Item",
      },
      {
        id: "3",
        title: "Third Item",
      },
      {
        id: "4",
        title: "Fourth Item",
      },
      {
        id: "5",
        title: "Fifth Item",
      },
      {
        id: "6",
        title: "Sixth Item",
      },
      {
        id: "7",
        title: "Seventh Item",
      },
      {
        id: "8",
        title: "Eighth Item",
      },
      {
        id: "9",
        title: "Nineth Item",
      },
      {
        id: "10",
        title: "Tenth Item",
      },
      {
        id: "11",
        title: "Eleventh Item",
      },
      {
        id: "12",
        title: "Twelveth Item",
      },
      {
        id: "13",
        title: "Thirteenth Item",
      },
      {
        id: "14",
        title: "Fourteenth Item",
      },
      {
        id: "15",
        title: "Fifteenth Item",
      },
    ];
    
    const Item = ({ title }) => (
      <View style={styles.item}>
        <Text style={styles.title}>{title}</Text>
      </View>
    );
    
    const App = () => {
      const [Viewable, SetViewable] = React.useState(null);
      const ref = React.useRef(null);
    
      const onViewRef = React.useRef((viewableItems) => {
         console.log(viewableItems.viewableItems[0]) //<-----here log
           //viewableItems<-- it is all items which are currently visible to you.
        SetViewable(viewableItems.viewableItems[0].item);
      });
    
      const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 80 });
    
      const Render_FlatList_Sticky_header = () => {
        return (
          <>
            <Text>hello{Viewable?.id}</Text>
          </>
        );
      };
      return (
        <SafeAreaView style={styles.container}>
          <FlatList
            data={DATA}
            renderItem={({ item }) => <Item title={item.title} />}
            keyExtractor={(item) => item.id}
            stickyHeaderIndices={[0]}
            ListHeaderComponent={Render_FlatList_Sticky_header}
            ref={ref}
            onViewableItemsChanged={onViewRef.current}
            viewabilityConfig={viewConfigRef.current}
          />
        </SafeAreaView>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      item: {
        backgroundColor: "#f9c2ff",
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
      },
      title: {
        fontSize: 32,
      },
    });
    
    export default App;
    

    You can play with the visible item and get desired output you want.

    You want this if Item.id=1 then my sticky Header text is "A",
    Then now you have the top item so add the switch case in Render_FlatList_Sticky_header based on the Viewable variable.

    as this:

    const checkSwitch = (param) => {
        switch (param) {
          case "1":
            return "A";
            break;
    
          case "2":
            return "B";
            break;
    
          case "3":
            return "C";
            break;
    
          case "4":
            return "D";
            break;
    
          default:
            return "AA";
        }
      };
    
      const Render_FlatList_Sticky_header = () => {
        return (
          <>
            <Text>hello{checkSwitch(Viewable?.id)}</Text>
          </>
        );
      };
    
    Login or Signup to reply.
  2. you can use the state to set the header dynamically.

    import { FlatList } from 'react-native';
    
    const MyList = ({ data }) => {
      const [headerText, setHeaderText] = useState('');
    
      const handleViewableItemsChanged = ({ viewableItems }) => {
        if (viewableItems && viewableItems.length > 0) {
          const firstViewableItem = viewableItems[0];
          setHeaderText(`Item ID: ${firstViewableItem.item.id}`);
        }
      };
    
      return (
        <View>
          <Text>{headerText}</Text>
          <FlatList
            data={data}
            keyExtractor={item => item.id}
            renderItem={({ item }) => <Text>{item.name}</Text>}
            onViewableItemsChanged={handleViewableItemsChanged}
            viewabilityConfig={{
              itemVisiblePercentThreshold: 50
            }}
          />
        </View>
      );
    };
    
    Login or Signup to reply.
  3. I guess this is what you want to achieve

     import React, {useEffect, useState} from 'react';
        import {FlatList, Text, View} from 'react-native';
        
        const DATA = [
          {name: 'Movies', header: true},
          {name: 'Interstellar', header: false},
          {name: 'Dark Knight', header: false},
          {name: 'Pop', header: false},
          {name: 'Pulp Fiction', header: false},
          {name: 'Burning Train', header: false},
          {name: 'Music', header: true},
          {name: 'Adams', header: false},
          {name: 'Nirvana', header: false},
          {name: 'Amrit Maan', header: false},
          {name: 'Oye Hoye', header: false},
          {name: 'Eminem', header: false},
          {name: 'Places', header: true},
          {name: 'Jordan', header: false},
          {name: 'Punjab', header: false},
          {name: 'Ludhiana', header: false},
          {name: 'Jamshedpur', header: false},
          {name: 'India', header: false},
          {name: 'People', header: true},
          {name: 'Jazzy', header: false},
          {name: 'Appie', header: false},
          {name: 'Baby', header: false},
          {name: 'Sunil', header: false},
          {name: 'Arrow', header: false},
          {name: 'Things', header: true},
          {name: 'table', header: false},
          {name: 'chair', header: false},
          {name: 'fan', header: false},
          {name: 'cup', header: false},
          {name: 'cube', header: false},
        ];
        const App = () => {
          const [stickyHeaderIndices, setStickyHeaderIndices] = useState([0]);
        
          useEffect(() => {
            var arr = [];
            DATA.map((obj, key) => {
              if (obj.header) {
                arr.push(DATA.indexOf(obj));
              }
            });
            arr.push(0);
            setStickyHeaderIndices(arr);
          }, []);
        
          renderItem = ({item}) => {
            if (item.header) {
              return (
                <View style={{width: '100%', height: 40, backgroundColor: '#fff'}}>
                  <Text style={{fontWeight: 'bold', fontSize: 16, textAlign: 'center'}}>
                    {item.name}
                  </Text>
                </View>
              );
            } else if (!item.header) {
              return (
                <View style={{width: '100%', height: 30, borderWidth: 1}}>
                  <Text style={{fontSize: 16}}>{item.name}</Text>
                </View>
              );
            }
          };
        
          return (
            <FlatList
              data={DATA}
              renderItem={item => renderItem(item)}
              keyExtractor={item => item.name}
              stickyHeaderIndices={stickyHeaderIndices}
            />
          );
        };
        export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search