React Native how to change last collapsed elements style

Viewed 49

If the last collapsed item is opened its bottom border should be removed, but all the other collapsable components should have a bottom border. How can i remove the bottom border of the last of type element? In React i could use :last-of-type but how to achieve this with React Native? Summary : How to change style of last collapsed item, without using any third party library?

remove border

   export function Dropdown() {
    return <View>{children}</View>;
}
export function ColapseItem() {
    const [isCollapsed, setIsCollapsed] = React.useState(collapsedByDefault ?? true);

    function onToggle() {
        setIsCollapsed((isCollapsed) => !isCollapsed);
    }

    return (
        <View>
            <Pressable style={itemStyles.container} onPress={onToggle}>
                <Text>{title}</Text>
                    <Icon size={14} name='icon1' />
            </Pressable>
            {!isCollapsed && <View style={itemStyles.collapsibleItem}>{children}</View>}
        </View>
    );
}

const itemStyles = StyleSheet.create({
    container: {
        justifyContent: "space-between",
        flexDirection: "row",
        borderBottomWidth: 1,
        borderBottomColor: 'red'
        paddingVertical: 20,
    },
    collapsibleItem: {
        paddingVertical: 20,
    },

});

children file

   <ColapseItem title="Label">
      <Text>children</Text>
   </ColapseItem>

   <ColapseItem title="Label">
      <Text>children</Text>
   </ColapseItem>

   <ColapseItem title="Label">
      <Text>children</Text>
   </ColapseItem>
1 Answers

You can use React.Children.map and React.cloneElement API's. With React.Children.map you can find the index of the child you want to add something. With React.clonElement you can copy this child and add style to it.

I also found a similar problem on: stackoverflow React: Mapping children of a parent component

Remember that you need to get to the Text child that is in the ColapseItem child.

Related