Search code examples
arraysjsonreact-nativeassetsreact-props

Access an object inside an other who is set as variable in React Native


I want to access an object property inside an object I call from an asset file :

const services = {
    
    facebook: {
        name: "facebook",
        color: "#28A2F3"
    },
    spotify: {
        name: "spotify",
        color: "#42D778"
    }
    
  }

  module.exports = services

My component :

export default function PasswordCard({icon, color}, props) {
    return (
        <View style={{
            padding: 20,
            backgroundColor: service[props.site].color,
            elevation: 2,
            borderRadius: 5,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-evenly",
            marginTop:5,
            marginBottom: 5,
        }}>
            <Icon style={styles.service} name={service[props.site].name} size={27} color="white" />
            <View style={styles.TextContainer}>
                <Text style={styles.Text}>[email protected]</Text>
                <Text style={styles.Text}>+213 (0) 384639293</Text>
            </View>
            <TouchableHighlight style={styles.icon}>
                <BenjaminButton name="eye" size={22} color="white" />
            </TouchableHighlight>
        </View>
    )
}

Where I call my component with the prop I pass :

<View style={styles.CardContainer}>
   <PasswordCard site={"facebook"} />
   <PasswordCard site={"spotify"} />
</View>

The error I got anyway :

TypeError: undefined is not an object (evaluating 'service[props.site].color')

But when I try accessing with service.facebook.name there's no error.


Solution

  • Props is always the first parameter so when you access props as the second parameter it will be undefined and when you use it you get the above error

    If you change your component like below

    function PasswordCard({icon, color,site}) {
    

    And styles like below

    backgroundColor: service[site].color,
    

    It will work. Also you should change other places where you refer this.