Search code examples
reactjsreact-nativereact-native-flatlist

Why does conditional rendering in FlatList showing unordered result


I wanted to implement the conditional rendering in the FlatList, so i used the below logic. This the code for FlatList.

<View style={styles.container}>
            <FlatList
                data={Object.keys(props.results)}
                numColumns={3}
                extraData={Object.keys(props.results)}
                keyExtractor={(item, index) => 'key' + index}
                renderItem={({item}) => {
                   **return renderMessage(item, props)**
                }}/>
        </View>

This is the code of the condition:

 const renderMessage = (item, props) => {
        if (props.results[item].opted) {
            console.log("inside if")
            return (
                <TouchableOpacity>
                    <ResultsDetail results={props.results[item]}
                                   setResults={props.setResults}
                                   setUserInterestResults={props.setUserInterestResults}> </ResultsDetail>
                </TouchableOpacity>
            );
        }
    }

I'm getting the results in the gridview, but its not ordered. I think its getting sorted or displayed based on the index. Please find the out as below.

output

How can i arrange it in order? Can you guys please help me with this?


Solution

  • Try this

    <View style={styles.container}>
        <FlatList
            data={Object.keys(props.results).filter((item => item.opted === true ? return item))}
            numColumns={3}
            extraData={Object.keys(props.results).filter((item => item.opted === true ? return item))}
            keyExtractor={(item, index) => 'key' + index}
            renderItem={({ item }) => renderMessage(item, props)} />
    </View>
    
    
    const renderMessage = (item, props) => {
        return (
            <TouchableOpacity>
                <ResultsDetail results={props.results[item]}
                    setResults={props.setResults}
                    setUserInterestResults={props.setUserInterestResults}> </ResultsDetail>
            </TouchableOpacity>
        );
    }