Search code examples
javascriptfunctionreact-nativecomponentsstateless

Passing function inside a stateless component is not working


I try to use a function inside of my stateless component. But it's not working properly.


const selectedColor = function ({color}) {
    switch (color) {
        case 'green':
            return styles.green;
            break;
        case 'blue':
            return styles.blue;
            break;
        case 'red':
            return styles.red;
            break;
        default:
            Alert.alert("Undefined Color!");
    }
}
const LightBulb = ({isLit, lightColor}) => {



    return (
        <View
            style={[isLit ? selectedColor(lightColor) : styles.green, {alignSelf: 'stretch'}]}>
            <Text>{isLit ? 'ON' : 'OFF'}</Text>
        </View>
    );


}



When isLit is true, selectedColor(lightColor) should be triggered. And once it is triggered, even lightColor is one of greed,red, or blue, it goes to Alert. Can you explain why this happens? And could someone give me a correct way of doing this?


Solution

  • I have made a few changes in your code and it's working now, Demo is here.

    https://snack.expo.io/@waheed25/smiling-carrot

    or here is the code which is running, You just need to pass your color in your function and it will be shown.

    import { View, Text } from 'react-native'
    import React, {useState} from 'react'
    
    const App =()=>{
      const [isLit, setIsLit] = useState(true)
    const selectedColor = (color)=> {
      console.log('color:', color)
        switch (color) {
            case 'green':
                return {backgroundColor: 'green'};
            case 'blue':
                return {backgroundColor: 'blue'};
            case 'red':
                return {backgroundColor: 'red'};
            default:
                Alert.alert("Undefined Color!");
        }
    }
        return (
            <View
                style={[isLit ? selectedColor('red') : {backgroundColor: 'green'}, {alignSelf: 'stretch', height: 200}]}>
                <Text>{isLit ? 'ON' : 'OFF'}</Text>
            </View>
        );
    
    }
    
    export default App;