to accommodate different screen sizes, react native offers flexbox support.
we will use the same code that we used in our react native - styling chapter. we will only change the presentationalcomponent.
layout
to achieve the desired layout, flexbox offers three main properties − flexdirection justifycontent and alignitems.
the following table shows the possible options.
| property | values | description |
|---|---|---|
| flexdirection | 'column', 'row' | used to specify if elements will be aligned vertically or horizontally. |
| justifycontent | 'center', 'flex-start', 'flex-end', 'space-around', 'space-between' | used to determine how should elements be distributed inside the container. |
| alignitems | 'center', 'flex-start', 'flex-end', 'stretched' | used to determine how should elements be distributed inside the container along the secondary axis (opposite of flexdirection) |
if you want to align the items vertically and centralize them, then you can use the following code.
app.js
import react, { component } from 'react'
import { view, stylesheet } from 'react-native'
const home = (props) => {
return (
<view style = {styles.container}>
<view style = {styles.redbox} />
<view style = {styles.bluebox} />
<view style = {styles.blackbox} />
</view>
)
}
export default home
const styles = stylesheet.create ({
container: {
flexdirection: 'column',
justifycontent: 'center',
alignitems: 'center',
backgroundcolor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundcolor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundcolor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundcolor: 'black'
},
})
output
if the items need to be moved to the right side and spaces need to be added between them, then we can use the following code.
app.js
import react, { component } from 'react'
import { view, stylesheet } from 'react-native'
const app = (props) => {
return (
<view style = {styles.container}>
<view style = {styles.redbox} />
<view style = {styles.bluebox} />
<view style = {styles.blackbox} />
</view>
)
}
export default app
const styles = stylesheet.create ({
container: {
flexdirection: 'column',
justifycontent: 'space-between',
alignitems: 'flex-end',
backgroundcolor: 'grey',
height: 600
},
redbox: {
width: 100,
height: 100,
backgroundcolor: 'red'
},
bluebox: {
width: 100,
height: 100,
backgroundcolor: 'blue'
},
blackbox: {
width: 100,
height: 100,
backgroundcolor: 'black'
},
})