Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent FlatList data inside child FlatList

I am rendering multiple FlatList children inside a parent FlatList like so

<FlatList
    data={parenttypes}
    renderItem={({item})=><View>
            <Text>{item.name}</Text>
            <FlatList
                data={childtypes}
                renderItem={({item})=><View>
                    <Text>HOW DO I ACCESS PARENT'S item here as well</Text>
                </View>}
            />      
    </View>}
/>

How can I access parent FlatList's item inside child FlatList?

like image 862
Singh Avatar asked Mar 08 '23 06:03

Singh


1 Answers

One simple solution is, instead of using arrow function for child FlatList, create separate function and bind the parent data inside child callback method.

Like this:

<FlatList
    data={parenttypes}
    renderItem={({item})=><View>
            <Text>{item.name}</Text>
            <FlatList
                data={childtypes}
                renderItem={this._renderChildItem.bind(this, item)}
            />      
    </View>}
/>

_renderChildItem(parentData, {item}) {
    console.log('data', parentData, item);
    return (    
        <View>
            <Text>HOW DO I ACCESS PARENT'S item here as well</Text>
        </View>
    )
}

Not sure but try this one also:

<FlatList
    data={parenttypes}
    renderItem={({item}) => { 
        let parentData = item;
        return (
            <View>
                <Text>{item.name}</Text>
                <FlatList
                    data={childtypes}
                    renderItem={({item}) => {
                        console.log('data', parentData, item);
                        return(
                            <View>
                                <Text>HOW DO I ACCESS PARENT'S item here as well</Text>
                            </View>
                        )
                    }
                />      
            </View>
        )
    }
/>
like image 66
Mayank Shukla Avatar answered Mar 15 '23 04:03

Mayank Shukla