Search code examples
javascriptreactjsreact-nativereduxreact-native-flatlist

How to select First item in FlatList as default one?


I'm trying to use Flatlist like Sidebar, but it intializes only after clicking on it, Is there any way by which I can make first flatlist item as default one. In other words onclick work should happen before page load like in lifecycleHooks Also suggest me If there is any way to create sidebar dynamically instead of using Flatlist

<FlatList
  data={Object.keys(this.state.groups)}
  renderItem ={({ item, index }) => 
  (
    <TouchableOpacity
      onPress={() => { this.showDetails(item),this.setState({itemIndex:index}) }}
      // onPress={() => alert(item)}
    >
    {console.log(index,"index of cards",Object.keys(this.state.groups),"item index")}  
    <View style={{width: 280, height:54 , flexDirection:"row",alignItems:"center",backgroundColor: (this.state.itemIndex === index) ? "#74C947" : "#F6F6F6"}}>
    {/* Use ExcludeIcon.svg  for stop symbol*/}
    {(this.state.itemIndex === index) ? 
    <Image source={require("../../../assets/images/WhiteTick.svg")} style={{width:16,height:11,marginLeft:15,marginRight:9}}/>            
    : 
    <Image source={require("../../../assets/images/GreenTick.svg")} style={{width:16,height:11,marginLeft:15,marginRight:9}}/>
    } 
    <Text style={{
      fontStyle:"normal",
      fontWeight:"500",
      fontSize: 16,              
      color: (this.state.itemIndex === index) ? "#FFFFFF" : "#333333",
      textTransform:"capitalize"
    }}>
      {item}
    </Text>
    </View>
  </TouchableOpacity>
  )
}
  keyExtractor={item => item}
 />

Before On click

After On Click


Solution

  • Try this way

     state = {
       itemIndex: 0
     };
    
    componentDidMount(){
      this.showDetails(this.state.itemIndex);
    }