Search code examples
react-nativereact-hooksreact-propsreact-native-stylesheet

React Native - Changing Color of Custom Component Button with Prop


I created a custom component. onPress and title have prop method but I also want to add another prop for setting color. The structure I try to make is like below

<TextButton color="red" onPress=... title=... />

My custom TextButton component file is here.

const TextButton = ({ onPress, title, color }) => {

    return (<TouchableOpacity onPress={onPress}><Text style={[styles.helpButton]}>{title}</Text></TouchableOpacity>
    );
}
const styles = StyleSheet.create({
    logButton: {
        fontSize: 18,
        fontWeight: 'bold',
        padding: 25,
        color: {color}
    },
});

I couldn't find how to add prop to change one specific style. How can I add color as prop?


Solution

  • You can achieve that by creating a new object based on the default style object.

    const TextButton = ({ onPress, title, color }) => {
        return (
            <TouchableOpacity onPress={onPress}>
                <Text style={{...styles.helpButton, color: color || "black"}}>{title}</Text>
            </TouchableOpacity>
        );
    };
    
    

    It's good to add a default case, like, if you forget to pass a color, it just uses "black" as your text color. If you feel like this line is too big, you can extract that into a function, it would look something like that:

    const TextButton = ({ onPress, title, color }) => {
        const addColor = (style, color) =>{
            return {
                ...style,
                color: color || "black"
            }
        }
    
        return (
            <TouchableOpacity onPress={onPress}>
                <Text style={addColor(styles.helpButton, color)}>{title}</Text>
            </TouchableOpacity>
        );
    };