I'm new to flexbox and am unable to produce a full width button in react-native. I've been trying to figure this out myself for over a day and have read every related article / post on the internet to no avail.
I would like to have two TextInput
elements that span the entire width of the screen, with a button below them that also spans the full width of the screen. The TextInput
elements are spanning the full width of the screen, but this appears to be by default in the Android simulator I'm running.
Here's my code:
var MyModule = React.createClass({ render: function() { return ( <View style={styles.container}> <View style={styles.headline}> <Text>Hello World</Text> </View> <View style={styles.inputsContainer}> <TextInput style={[styles.input]} placeholder="Email" /> <TextInput secureTextEntry={true} style={[styles.input]} placeholder="Password" /> <TouchableHighlight style={styles.fullWidthButton} onPress={this.buttonPressed} > <Text>Submit</Text> </TouchableHighlight> </View> </View> ); }, buttonPressed: function() { console.log("button was pressed!"); } }); var paddingLeft = 15; var styles = StyleSheet.create({ inputsContainer: { // Intentionally blank because I've tried everything & I'm clueless }, fullWidthButton: { // Intentionally blank because I've tried everything & I'm clueless }, input: { paddingLeft: paddingLeft, height: 40, borderColor: "black", backgroundColor: "white" }, container: { flex: 1, backgroundColor: "#f0f0f0", alignItems: "stretch" }, headline: {} }); module.exports = Onboarding;
Anyone know what I need to do to get the TouchableHighlight
to span the full width of the screen?
display: block and width: 100% is the correct way to go full width but you need to remove the left/right margin on the button as it pushes it outside the containing element. for more information on the box-sizing property, read the MDN docs.
Flexbox is designed to provide a consistent layout on different screen sizes. You will normally use a combination of flexDirection , alignItems , and justifyContent to achieve the right layout. Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions.
I came here looking for the same question. Having experimented further, I've found the simplest way is to use alignSelf: 'stretch'
. This forces the individual element to take up the full width available e.g.
button: { alignSelf: 'stretch' }
Nader's answer does work of course, but this would seem to be the correct way using Flexbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With