Home > OS >  How do I pass a prop to a stylesheet in React Native?
How do I pass a prop to a stylesheet in React Native?

Time:11-07

I have a prop called isProfile which is used by a component (Feed) that uses the stylesheet below. I want to conditionally render the height of the container based on whether the isProfile prop is set as true or false.

function Feed({isProfile}){
    return(
      <View style={style.container}>
      </View>

)

}

    
const styles =  StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",
       height: isProfile ? windowHeight : windowHeight*0.87,

    },

CodePudding user response:

This is how I solved my problem.

I changed my styleSheet code as such

const styles = (isProfile) => StyleSheet.create({
container:{

   backgroundColor:colors.primary,           
   width:windowWidth,
   justifyContent:"center",
   height: isProfile ? windowHeight : windowHeight*0.87,

},
)}

And then I passed to prop to the styleSheet as such

        <View style={styles(isProfile).container}>
        </View>

CodePudding user response:

You should change styles to a function that accepts the parameter:

function Feed({isProfile}){
    return(
      <View style={createStyles(isProfile).container}>
      </View>

)

}


const createStyles = (profile) => StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",
       height: profile ? windowHeight : windowHeight*0.87,

    },

The isProfile variable (prop) is local to the component and invisible outside, so it must be passed as the parameter

CodePudding user response:

You can store mutiple styles by using an array of objects for style style={[{},{}]} etc.. This allows you to add the second part I added

function Feed({isProfile}){
    return(
      <View style={[style.container,{height: isProfile ? windowHeight : windowHeight*0.87,}]}>
      </View>

)

}

    
const styles =  StyleSheet.create({
    container:{
       backgroundColor:colors.primary,                     
       width:windowWidth,
       justifyContent:"center",

    },
  • Related