Home > Net >  dynamic customizable button in react native
dynamic customizable button in react native

Time:10-12

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; 

CodePudding user response:

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; 

CodePudding user response:

Use `` for template literals not ' '.

  • Related