Categories
React Native

React Native — Flexbox Layout

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

Layout with Flexbox

We can use flexbox for layouts with React Native.

It works the same way as CSS.

Flex

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{ flex: 1, flexDirection: 'column' }}>
      <View style={{ width: 50, height: 50, backgroundColor: 'powderblue' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'skyblue' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'steelblue' }} />
    </View>
  );
}

We create a column layout by setting flexDirection to 'column' on the outer view.

Then the inner views have their own dimensions set.

Layout Direction

The default direction for layouts is left to right.

It can also be set to right to left.

Justify Content

We can set the justifyContent property to spread the content the way we want.

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{
      flex: 1,
      flexDirection: 'column',
      justifyContent: 'space-between',
    }}>
      <View style={{ width: 50, height: 50, backgroundColor: 'powderblue' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'skyblue' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'steelblue' }} />
    </View>
  );
}

We have flexDirection set to 'column' and justifyContent set to 'space-between' .

Therefore, the inner views will be spread evenly in a column.

Align Items

We can set the alignItems property to align the items.

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{
      flex: 1,
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'stretch',
    }}>
      <View style={{ height: 50, backgroundColor: 'powderblue' }} />
      <View style={{ height: 50, backgroundColor: 'skyblue' }} />
      <View style={{ height: 50, backgroundColor: 'steelblue' }} />
    </View>
  );
}

We set alignItems to 'stretch' , so the inner views will stretch across the screen.

Other values for alignItems can be 'flex-start' , 'center' , or 'flex-end' .

Align Self

The alignSelf property is also available with React Native.

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{
      flex: 1,
      flexDirection: 'column',
      justifyContent: 'center',
    }}>
      <View style={{ width: 50, height: 50, backgroundColor: 'powderblue', alignSelf: 'flex-end' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'skyblue' }} />
      <View style={{ width: 50, height: 50, backgroundColor: 'steelblue' }} />
    </View>
  );
}

to add the alignSelf property to our first inner view.

It’s set to 'flex-end' so it’ll be put on the right side.

Conclusion

We can use many flexbox properties to create layouts with React Native.

Categories
React Native

React Native — View Styles

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

View Style Props

We can set styles for views.

For example, we can write:

import React from 'react';
import { View, StyleSheet } from "react-native";

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.top} />
      <View style={styles.middle} />
      <View style={styles.bottom} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "space-between",
    backgroundColor: "#fff",
    padding: 20,
    margin: 10,
  },
  top: {
    flex: 0.3,
    backgroundColor: "grey",
    borderWidth: 5,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
  },
  middle: {
    flex: 0.3,
    backgroundColor: "beige",
    borderWidth: 5,
  },
  bottom: {
    flex: 0.3,
    backgroundColor: "pink",
    borderWidth: 5,
    borderBottomLeftRadius: 20,
    borderBottomRightRadius: 20,
  },
});

We use common CSS properties to set the style of the views.

flex is the proportion of the screen that the view takes.

justifyContent sets the alignment for the content.

backgroundColor sets the background color.

borderWidth sets the border width of the view.

padding sets the padding of the view.

margin sets the margin of the view.

PressEvent Object Type

The PressEvent object has various properties.

This type of object is set as the event object when a button is pressed.

For example, if we have:

import React from 'react';
import { View, StyleSheet, Text, SafeAreaView, Button } from "react-native";

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <View>
        <Button
          title="Press me"
          onPress={(ev) => console.log(ev)}
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginHorizontal: 16,
  }
});

We log the event object for button presses, which should be a PressEvent .

It has many properties, including:

{
    changedTouches: [PressEvent],
    identifier: 1,
    locationX: 8,
    locationY: 4.5,
    pageX: 24,
    pageY: 49.5,
    target: 1127,
    timestamp: 85131876.58868201,
    touches: []
}

identifier is the ID of the button press.

locationX is the x-coordinate of the button press.

locationY is the y-coordinate of the button press.

pageX is the touch origin’s x-coordinate on the screen.

pageY is the touch origin’s y-coordinate on the screen.

target is the ID of the element receiving the press event.

timestamp is the timestamp when the PressEvent occurred in milliseconds.

Height and Width

We can set the height and width of components.

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View>
      <View style={{ width: 50, height: 50, backgroundColor: 'powderblue' }} />
    </View>
  );
}

We set the width and height properties to set the width and height of the View .

Also, we can use flexbox to set the dimensions.

For example, we can write:

import React from 'react';
import { View } from 'react-native';

export default function App() {
  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 1, backgroundColor: 'powderblue' }} />
    </View>
  );
}

We set the flex property of the views to fill the outer View with the inner View .

Conclusion

We can set various styles for views.

Also, we can get data from button press events.

Categories
React Native

React Native — Layouts and Fonts

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

Layout Props

We can control the layout of our app with some props.

For example, we can write:

import React from 'react';
import { View } from "react-native";

const randomHexColor = () => {
  return '#000000'.replace(/0/g, () => {
    return (~~(Math.random() * 16)).toString(16);
  });
};

const Square = () => {
  const sqStyle = {
    width: 50,
    height: 50,
    backgroundColor: randomHexColor(),
  };
  return <View style={sqStyle} />;
};

export default function App() {
  return (
    <View style={{
      flexDirection: 'row',
      justifyContent: 'flex-start',
      alignItems: 'flex-start'
    }}>
      <Square />
      <Square />
      <Square />
    </View>
  );
}

We added some squares with the Square component.

Then we set the style of the View with some flexbox properties.

We can use all the flexbox properties like flexDirection , justifyContent , alignItems , etc.

And we can set them to the value that we want.

Shadow Props

We can set a shadow on a container by setting the shadowOffset property.

For example, we can write:

import React from 'react';
import { View, StyleSheet } from "react-native";
const shadowOffsetWidth = 20;
const shadowOffsetHeight = 20;
const shadowOpacity = 0.5;
const shadowRadius = 10;

export default function App() {
  return (
    <View style={styles.container}>
      <View style={[
        styles.square,
        {
          shadowOffset: {
            width: shadowOffsetWidth,
            height: -shadowOffsetHeight
          },
          shadowOpacity,
          shadowRadius
        }
      ]}>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "space-around",
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  square: {
    alignSelf: "center",
    backgroundColor: "white",
    borderRadius: 4,
    height: 150,
    shadowColor: "black",
    width: 150
  },
  controls: {
    paddingHorizontal: 12
  }
});

We set the width and height of the shadow offset within the shadowOffset property.

Also, we set the shadow’s opacity with the shadowOpacity property.

And we set the shadow’s radius with the shadowRadius property.

Text Style Props

We can set styles for text.

For example, we can write:

import React from 'react';
import { View, StyleSheet, Text } from "react-native";
const fontStyles = ["normal", "italic"];
const fontVariants = [
  undefined,
  "small-caps",
  "oldstyle-nums",
  "lining-nums",
  "tabular-nums",
  "proportional-nums"
];
const fontWeights = [
  "normal",
  "bold",
  "100",
  "200",
  "300",
  "400",
  "500",
  "600",
  "700",
  "800",
  "900"
];
const textAlignments = ["auto", "left", "right", "center", "justify"];
const textDecorationLines = [
  "none",
  "underline",
  "line-through",
  "underline line-through"
];
const textDecorationStyles = ["solid", "double", "dotted", "dashed"];
const textTransformations = ["none", "uppercase", "lowercase", "capitalize"];
const textAlignmentsVertical = ["auto", "top", "bottom", "center"];
const writingDirections = ["auto", "ltr", "rtl"];

export default function App() {
  return (
    <View style={styles.container}>
      <Text
        style={[
          styles.paragraph,
          {
            fontSize: 20,
            fontStyle: fontStyles[0],
            fontWeight: fontWeights[0],
            lineHeight: 200,
            textAlign: textAlignments[0],
            textDecorationLine: textDecorationLines[0],
            textTransform: textTransformations[0],
            textAlignVertical: textAlignmentsVertical[0],
            fontVariant: fontVariants[0],
            letterSpacing: 5,
            includeFontPadding: true,
            textDecorationStyle: textDecorationStyles[0],
            writingDirection: writingDirections[0],
            textShadowOffset: {
              height: 10,
              width: 10
            },
            textShadowRadius: 5
          }
        ]}
      >
        Lorem Ipsum
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "space-around",
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  paragraph: {
    color: "black",
    textDecorationColor: "yellow",
    textShadowColor: "red",
    textShadowRadius: 1,
    margin: 24
  }
});

to set all the styles for our text.

fontSize sets the font size.

fontStyle sets the font style.

lineHeight sets the line-height.

textAlign sets the text alignment.

textDecorationLine sets the text style.

textTransform lets us transform the text.

fontVariant sets the font-variant.

letterSpacing sets the letter spacing.

writingDirection sets the direction of the text.

textShadowOffset sets the shadow’s position.

textShadowRadius sets the radius of the shadow.

Conclusion

We can set many styles for fonts and layouts.

Categories
React Native

React Native — Status Bar and Image Styles

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

StatusBar

The StatusBar lets us control the status bar with our app.

For example, we can write:

import React, { useState } from 'react';
import { Button, StyleSheet, StatusBar, View } from "react-native";
import Constants from "expo-constants";

export default function App() {
  const [visibleStatusBar, setVisibleStatusBar] = useState(false);
  const changeVisibilityStatusBar = () => {
    setVisibleStatusBar(!visibleStatusBar);
  };

  return (
    <View style={styles.container}>
      <StatusBar backgroundColor="blue" barStyle='dark-content' />
      <View>
        <StatusBar hidden={visibleStatusBar} />
      </View>
      <View style={styles.buttonContainer}>
        <Button title="Toggle StatusBar" onPress={() => changeVisibilityStatusBar()} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Constants.statusBarHeight,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'pink',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We added a StatusBar that can be toggled with the hidden prop.

And we also added one that has the backgroundColor set to 'blue' .

The barStyle sets the status bar style, which is 'dark-content' .

It can also be set to 'default' and ‘light-content’ .

Image Style Props

We can set our image to display with the style we want.

For example, we can write:

import React from 'react';
import { View, Image } from "react-native";

export default function App() {
  return (
    <View>
      <Image
        style={{
          resizeMode: "cover",
          height: 100,
          width: 200
        }}
        source={{ uri: 'https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo' }}
      />
    </View>
  );
}

to set the width and height .

The resizeMode sets how the image is resized.

We can set it to 'cover' , 'contain' , 'stretch' , 'repeat' , or 'center' .

Also, we can set the tint color. For example, we can write:

import React from 'react';
import { View, Image } from "react-native";

export default function App() {
  return (
    <View>
      <Image
        style={{
          tintColor: "lightgreen",
          resizeMode: "contain",
          height: 100,
          width: 200
        }}
        source={{ uri: 'https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo' }}
      />
    </View>
  );
}

Then we can see that the image is a light green box instead of showing the original image.

Also, we can add a border around our image.

For example, we can write:

import React from 'react';
import { View, Image } from "react-native";

export default function App() {
  return (
    <View>
      <Image
        style={{
          borderColor: "red",
          borderWidth: 5,
          height: 100,
          width: 200
        }}
        source={{ uri: 'https://reactnative.dev/docs/assets/p_cat2.png' }}
      />
    </View>
  );
}

We set the borderColor to 'red' and borderWidth to 5 to add the border.

Also, we can add border-radius to an image by writing:

import React from 'react';
import { View, Image } from "react-native";

export default function App() {
  return (
    <View>
      <Image
        style={{
          borderTopLeftRadius: 10,
          borderTopRightRadius: 10,
          borderBottomLeftRadius: 10,
          borderBottomRightRadius: 10,
          height: 100,
          width: 200
        }}
        source={{ uri: 'https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo' }}
      />
    </View>
  );
}

We set the border-radius for the image for each corner with these properties.

Conclusion

We can control the status bar and manipulate images with React Native.

Categories
React Native

React Native — Modal, PixelRatio, and RefreshControl

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

Modal

We can add a modal to present content above the enclosing view.

For example, we can write:

import React, { useState } from 'react';
import {
  Alert,
  Modal,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from "react-native";

export default function App() {
  const [modalVisible, setModalVisible] = useState(false);
  return (
    <View style={styles.centeredView}>
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert("Modal has been closed.");
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello World!</Text>
            <TouchableHighlight
              style={styles.openButton}
              onPress={() => {
                setModalVisible(!modalVisible);
              }}
            >
              <Text style={styles.textStyle}>Hide Modal</Text>
            </TouchableHighlight>
          </View>
        </View>
      </Modal>
      <TouchableHighlight
        style={styles.openButton}
        onPress={() => {
          setModalVisible(true);
        }}
      >
        <Text style={styles.textStyle}>Show Modal</Text>
      </TouchableHighlight>
    </View>
  );
}

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5
  },
  openButton: {
    backgroundColor: "pink",
    borderRadius: 20,
    padding: 10,
    elevation: 2
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center"
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center"
  }
});

We add the View to enclose a Modal component with the modal.

The modal has the View to hold the content.

The TouchableHighlight component is a button that lets us press it to close the modal.

The modal’s open state is opened by the modalVisible state.

The visible prop in the Modal sets the open state.

Below the Modal , we have another TouchableHighlight component to call setModalVisible with true to open it.

PixelRatio

The PixelRatio object gives us access to the device’s pixel density and the font scale.

We can use it to correctly size an image.

For example, we can write:

import React from 'react';
import { Image, PixelRatio, StyleSheet, View } from "react-native";

const size = 50;
const cat = {
  uri: "https://reactnative.dev/docs/assets/p_cat1.png",
  width: size,
  height: size
};

export default function App() {
  return (
    <View style={styles.container}>
      <Image
        source={cat}
        style={{
          width: PixelRatio.getPixelSizeForLayoutSize(size),
          height: PixelRatio.getPixelSizeForLayoutSize(size)
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: "center",
    alignItems: "center"
  },
  value: {
    fontSize: 24,
    marginBottom: 12,
    marginTop: 4
  }
});

We set the width and height in the Image component by calling PixelRatio.getPixelSizeForLayoutSize .

The pixel size will be rounded when we specify size with arbitrary precision.

Therefore, we’ve to be careful with rounding errors.

RefreshControl

We can add a RefreshControl component inside a ScrollView or ListView to add pull to refresh functionality.

For example, we can write:

import React from 'react';
import {
  ScrollView,
  RefreshControl,
  StyleSheet,
  Text,
  SafeAreaView,
} from 'react-native';
import Constants from 'expo-constants';

const wait = (timeout) => {
  return new Promise(resolve => {
    setTimeout(resolve, timeout);
  });
}

export default function App() {
  const [refreshing, setRefreshing] = React.useState(false);

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);

    wait(2000).then(() => setRefreshing(false));
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollView}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        <Text>Pull to Refresh</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: Constants.statusBarHeight,
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'pink',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We added the RefreshControl in the ScrollView to add the pull to refresh indicator that shows when we pull the screen down.

The refreshing prop controls when the RefreshControl is shown.

And onRefresh is run when we show the RefreshControl .

Conclusion

We can add a modal and refresh indicator into our React Native app.

Also, we can size image proportionally with the PixelRatio object.