Knevagi
Knevagi

Reputation: 157

When styling in react native flex=1 not working

Hello i am fairly new to React Native and am using flex=1 for making a button cover the entire width of the screen but that is not happening for some reason.

The script for creating the button component

The result in the emulator

Using the button component to create a button

Upvotes: 1

Views: 19259

Answers (3)

Tejas Bagul
Tejas Bagul

Reputation: 1

make ---> <View style = {{flex: 1}} > <----- in your app.js file.

Upvotes: 0

Daniel Gabor
Daniel Gabor

Reputation: 1526

-Flex:1 cover the entire width and height of its container.

-In your case your view (line 9) is taking the whole space available of its container which is the TouchableOpacity (line 8)

The problem is that the TouchableOpacity doesn't take the whole space available because you didn't give it that instruction.

Just add style={{flex:1}} to your TouchableOpacity and it should work

Upvotes: 5

shimatai
shimatai

Reputation: 1808

You can use TouchableOpacity as a View, so you can remove the inner <View>...</View> component from your Button and use only <TouchableOpacity style={styles.buttonStyle}><Text style={styles.textStyling}>Buy now</Text></TouchableOpacity>.

I don't know how is your CardSection component, but I can bet that setting flex: 1 to TouchableOpacity and removing nested View will solve your problem,.

You're using the style sheet in a wrong way. The correct way is to import StyleSheet from react-native, as follows:

import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  buttonStyle: {
    backgroundColor: "#f7f7f7",
    flex: 1, // This will be applied to TouchableOpacity
    flexDirection: 'row'
  },
  textStyling: {
     // ...
  }
});

I strong recommend you to take a look at Native Base (it's a set of components ready to use).

You can try this solution online accessing this snack

Upvotes: 0

Related Questions