cssreact-nativeflexboxreact-native-flexbox

Reduce space between React Native views


I am currently working on a React Native app with the following layout:

(full source code can be found at https://snack.expo.io/@ajaybhatta49/new-project, but I think the issue is in this file)

import React, {useState} from 'react'
import { View, StyleSheet } from 'react-native'
import CButton from './components/CButton'
import Display from './components/Display'

const buttonRows = [
  ["1", "2", "3", "+"],
  ["4", "5", "6", "-"],
  ["7", "8", "9", "x"],
  [".", "0", "<", "/"],
  ["CLEAR", "ENTER"]
]

export default function App(props) {
  const [input, setInput] = useState('')
  const handlePress = str => {
    if (str === "CLEAR") {
      setInput('')
    } else if (str === "ENTER") {
      try {
        setInput(eval(input))
      } catch(err) {
        setInput("SYNTAX ERROR")
      }
    } else if (str === "x") {
      setInput(`${input}*`)
    } else if (str === "<") {
      setInput(input.slice(0, input.length - 1))
    } else {
      setInput(input + str)
    }
  }
  return (
    <View style={styles.main}>
      <Display value={input}/>
      {buttonRows.map(buttons => {
        return (
          <View style={styles.inline}>
            {buttons.map(b => {
              return (
                <CButton title={b} handlePress={() => handlePress(b)}/>
              )
            })}
          </View>
        )
      })}
    </View>
  )
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    flexDirection: 'column',
    alignContent: 'center',
    justifyContent: 'space-evenly',
    alignItems: 'center',
    backgroundColor: '#222',
    padding: 5
  },
  inline: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    height: 5
  }
})

The app works fine, but I want to get rid of the extra space between the rows of buttons, and preferably align everything to the center vertically. I have tried changing the value of styles.main.justifyContent to space-evenly, space-around, flex-start, and center, none of which resolved the issue. I also tried a similar question's answer, which was to get rid of one of the flex: 1's, but the app crashes unless both of them are there. What should I do?


Solution

  • Whether justifyContent works vertically or horizontally depends on flex direction.So in styles.inline when you use flex while your direction is column, it makes the column take up all the vertical space it could. I removed height because it appearred to break the layout (idk why)

    const styles = StyleSheet.create({
      main: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#222',
        padding: 5
      },
      inline: {
        flexDirection: 'row',
      }
    })