Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SectionList get section index in renderSectionHeader

<SectionList
  sections={[{ data: [1, 2] }, { data: [3, 4] }]}
  renderItem={({ item, index }) => ...}
  renderSectionHeader={({ section, index }, i) => {
    console.log(index, i); // both undefined
  }}
/>

I want to get the index of the section in renderSectionHeader.
Eg. index should be 0 when section.data is [1, 2] and 1 when section.data is [3, 4].

How can I accomplish this apart from adding the index to the sections data?

like image 843
Avery235 Avatar asked May 12 '18 13:05

Avery235


2 Answers

There's no section index of renderSectionHeader in SectionList of react native but you can add an index prop to your sections like this

 sections={[{ data: [1, 2], index:0 }, { data: [3, 4], index:1 }]}

and then access the index in renderSectionHeader like this

 renderSectionHeader={({section}) => {
     console.log(section.index); 
 }}
like image 193
digit Avatar answered Sep 18 '22 14:09

digit


I know it is late but maybe It helps someone. A better way is to get the index of your section from the array you are passing to the SectionList component. For example supposing you have dataList as array which is passed to sections sections={dataList}, then you can get the index as following:

renderSectionHeader={({ section }) => {
    const index = dataList.indexOf(section)
    // Here you have the index
    return <View />
}}

Hope this helps.

like image 23
user2731717 Avatar answered Sep 17 '22 14:09

user2731717