Home > Software design >  how to style fist child in React Native
how to style fist child in React Native

Time:08-25

I need to apply marginLeft:4 to all elements except firs one for styles.option , how can i get to style only the first child in React Native? Is it possible not installing any new packages to the project?

 return (
        <View style={style}>
            <View style={styles.container}>
                {options.map((option) => (
                    <Option
                        checked={option.value === value}
                        key={option.value}
                        label={option.label}
                    />
                ))}
            </View>
        </View>
    );
}

function Option(){
  return (
        <Pressable
            style={[styles.option, checked && styles.checked]}
        >
            <Text>
                {label}
            </Text>
        </Pressable>
    );
}

const styles = StyleSheet.create({
    container: {
        padding: 4,
    },
    option: {
        marginLeft: 4,  //Need to apply this style to all elements except firs one
    },
    "option:first-child": {
        marginLeft: 0, //This does not work
    },

CodePudding user response:

Hey here is how you can do it, check answer

 return (
            <View style={style}>
                <View style={styles.container}>
                    {options.map((option,index) => (
                        <Option
                            index={index} // pass index like this
                            checked={option.value === value}
                            key={option.value}
                            label={option.label}
                        />
                    ))}
                </View>
            </View>
        );
    }
    
    function Option(props={}){
    const {index = 0} = props;
      return (
            <Pressable
                style={[styles.option, checked && styles.checked, {

marginLeft:index ===0? 0: 4 // here is how you do it
}]}
            >
                <Text>
                    {label}
                </Text>
            </Pressable>
        );
    }
    
    const styles = StyleSheet.create({
        container: {
            padding: 4,
            flexDirection: "row",
            backgroundColor: "gray",
        },
        option: {
            backgroundColor: "red",
            **marginLeft: 4,**  //Need to apply this style to all elements except firs one
            justifyContent: "center",
            alignItems: "center",
        },
        "option:first-child": {
            **marginLeft: 0,** //This does not work
        },
  • Related