skip to Main Content

i am trying to make a selectable button design by passing the "PRIMARY" or "TERTIARY" to type. i think there is a problem in the "styles[‘container_${type}’]" in line 7 but i cant figure it out

import { View, StyleSheet, Image ,Text, Pressable} from 'react-native';

function CustomButton({onPress, text, type}) {        
    return (           
        <Pressable                                                    
        onPress={onPress}            
        style={[styles.container, styles['container_${type}']]}>             
        <Text  style={[styles.text, styles['text_${type}']]} >{text}</Text>            
        </Pressable>
        );            
}    
const styles = StyleSheet.create({
    container:{
        
        width: '100%',
        padding: 15,
        alignItems: 'center',
        borderRadius: 30,
        marginVertical: 25,
    },
    container_PRIMARY:{
        backgroundColor: '#fde17d',
    },
    container_TERTIARY:{
        backgroundColor: 'pink',
    },

    text: {
        fontWeight: 'bold',
        color: 'white',
    },
    text_TERTIARY :{
        color: 'gray',
    }

})

export default CustomButton; 

2

Answers


  1. Try this,

    import { View, StyleSheet, Image ,Text, Pressable} from 'react-native';
    
    function CustomButton({onPress, text, type}) {   
        const stylesheet = type == 'PRIMARY' ? 'container_PRIMARY' : 'container_TERNIARY';    
        return (           
            <Pressable                                                    
            onPress={onPress}            
            style={[styles.container, {...stylesheet}]}>             
            <Text  style={[styles.text, styles['text_${type}']]} >{text}</Text>            
            </Pressable>
            );            
    }    
    const styles = StyleSheet.create({
        container:{
            
            width: '100%',
            padding: 15,
            alignItems: 'center',
            borderRadius: 30,
            marginVertical: 25,
        },
        container_PRIMARY:{
            backgroundColor: '#fde17d',
        },
        container_TERTIARY:{
            backgroundColor: 'pink',
        },
    
        text: {
            fontWeight: 'bold',
            color: 'white',
        },
        text_TERTIARY :{
            color: 'gray',
        }
    
    })
    
    export default CustomButton; 
    
    Login or Signup to reply.
  2. Use “ for template literals not ‘ ‘.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search