Start with React Native: Build an Expo Application
Guy with notebook

August 25, 2021

Start with React Native: Build an Expo Application

Patryk Kluczak

Frontend Developer
SHARE
frontend app(2)

Hello, My name is Patrick, and I really want to show you the basic steps for React Native. You will get a detailed explanation on how to instal the first app in React Native and add plugins with code examples. In other words - will give a decent dose of concrete React Native lifehacks about React Native for beginners. But first things first - let’s start from the general info.

In my article, I will focus on the application of the IOS and describe the basic changes between React and React Native. I decided to use an Expo framework, for me it’s quite better especially when it comes to using API references like camera or gyroscope.

Framework Expo has its own SDK library and for the basic app, you don’t have to install external plugins or create your own features in native languages like Java or Objective-C.

So what is React Native?

React Native is a mobile framework based on React.js - Facebook’s JavaScript library - which allows you to develop cross-platform applications for both Android and iOS. It used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows, and UWP.

React Native enables you to build mobile apps using only JavaScript with the same structure as React. This makes it possible to create a multifunctional mobile UI using declarative components.

Advantages of React Native

Cross-platform development

Applications written in React Native framework are cross-platform - its single codebase, which is written in JavaScript, creates both Android and IOS modules. The code is shared between platforms so it is much faster to develop for both of them. Thanks to React Native, users can enjoy the applications which feel and look like native, and developers have an opportunity to use the tool which is comfortable to work with. In React apps, we can still reuse some code between the mobile and web apps.

Time saving

React Native provides components for formats like text, images, links, animations, clipboards etc. These components make the process of development faster. The «Hot Reloading» feature also saves a lot of time for developers. Thanks to this possibility, the application is reloaded every time the JS file is saved, so UI development, testing and bug fixing processes are more optimised with React Native.

User experience

The application created with the help of React Native feels and looks completely native on every platform. You will not find any difference between native applications and cross-platform React apps!

Why React Native could be not the best choice?

If you are a JavaScript hater

Do you have a personal grudge against JavaScript? You wouldn't be a fan of React Native then. JavaScript is not like other traditional languages - that is why some people dislike React and React Native.

React Native is still new

React is in the active development stage now and it develops fast - it is much younger than other traditional Android and iOS development languages. As you noticed, guys from Frontend News podcast regularly talk about React releases and updates. React does not completely support all native features and libraries, but skilled developers can always deal with that.

Complicated to learn

React can be very challenging for beginners. But no worries - this article will help you with that.

That’s enough for the basics. Wait for the code heavy artillery!

You don’t have to spend time building your own React Native developers team. Save time and start working on your Android/iOS project right away with Frontend House.

Sneak peak about React Native

React Native is a very cool app writing tool, but can you do anything with it? The answer depends on whether we want to use Expo or not. If you decide to use Expo you should remember about restrictions to the native possibilities, but on the other hand, allows you to write native apps without Java or Objective-C. However if you have knowledge about the language mentioned above and have more patience to configure the dev environment, a better solution would be React Native without Expo Extension. For the more complicated problems, you will have to find a plugin or write a missing part of the code in native language for IOS and Android. So you have to decide which one will be better for you.

When should you create a React Native app?

Definitely if you have a web app created in React. The huge part of logic or design will be the same or really similar, when you want to expand possibilities of existing web apps only. The last - but not the least - argument is when you are a frontend developer and the app is not demanding very advanced device possibilities.

Installation the first app

So let’s begin.

First of all, we have to install the expo framework and just put this line in the terminal. npm install —global expo-cli

It will take a while but don’t worry worth it. :)

After successful installation, we can create a new app. Like before use terminal and put

expo init app-name where app-name is a project named.

At Fronted House, we use TypeScript to provide better security in our apps. I recommend this solution, so I choose the second option.

typescript image

When Instalator finished you see a similar file structure to the basic React app but not all elements are the same.

Starting developer server is very similar to a normal React app but we have to put the expo start in the command line.

Now, the browser should open a new page with localhost content. The default port is 19000 but if it occupied local server will take the next free number.

The manage panel has few options and allows sharing projects in an easy way or test on physical devices.

If you want to deploy on Android select the first option, but remember: firstly you have to install Android Studio with the newest Android SDK-Build-Tools.

Expo allows you to display results in the browser too, click on the third link “Run in web browser” and wait a little. On the new page will see the result.

Deployment on physical devices is a simple process. Open mobile browser and put the exp address or easier use QR code, but remember you will need an Expo GO application. You can download it from AppStore and GooglePlay.

We focus on the iOS simulator. Just click on the correct label like on the screen below: expo go image

Basic React Native Component

Basic components to create app:

  • View
  • Text
  • Image
  • Button
  • TouchableOpacity

Like you see the names are unambiguous and very easy to remember.

In the beginning, I want to show you how to add your own CSS to components. The workflow is the same as on React. By default we have two options, we can create a class or add style inline. Some examples below:

 export default function BasicHome() {
  return (
    <View style={styles.container}>
      <Image
        source={logo}
        style={{
          width: 300,
          height: 155,
          marginBottom: 30,
          resizeMode: 'contain',
        }}
      />
      <Text style={styles.intro>
        Welcome 
    </Text>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: 'flex',
    backgroundColor: '#f0f0f0',
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    height: '100%',
  },
  intro: {
    color: '#3E1CA1',
    fontSize: 28,
    fontWeight: '700',
    marginHorizontal: 15,
    marginBottom: 10,
  },
});

Results:

expo go image

Like you see, both style options work. You may be surprised why I used to display „flex” instead of „block”, so it’s one of the differences to the standard React. In native we have two options: flex or none. If you don't feel confident with flex keep the article

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Used Plugins

First of all we have to add plugins to the project. Like always it will be very simple. To install plugins to the project you can use npm or yarn.

First plugin it’s a react-navigation with @types/react-navigation of course if you use TypeScript in your project. ;) The extension is the counterpart to the react-router-dom for standard react projects.

Second plugin will be styled-components with @types/styled-components. It works in React Native too.

Last extension will be a language plugin. I chose react-intl with @types/react-intl but If you prefer the i18n framework don’t worry, you can use this one too.

For now we know what plugins will be needed so install them. yarn add react-navigation yarn add styled-components yarn add react-intl

On an android device you can see errors about missing Intl variables. The solution is very simple: yarn add intl.

Code examples

Here is an example without any rocket science. it’s really similar to the browser react app

import React from 'react';
import 'intl';
import { IntlProvider } from 'react-intl';
 
import Router from './components/Router';
import messages_en from './language/en.json';
 
interface messagesType {
 [name: string]: { [name: string]: string };
}
 
const messages: messagesType = {
 en: messages_en,
};
 
const App = () => {
 const language = navigator.language
   ? navigator.language.split(/[-_]/)[0]
   : 'en';
 
 return (
   <IntlProvider locale={language} messages={messages[language as string]}>
     <Router />
   </IntlProvider>
 );
};
 
export default App;

Ok now we can go ahead to the router component. In this place where we use Stack.Navigator and manage Stack.Screen are the counterparts of BrowserRouter.

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { ThemeProvider } from 'styled-components';
 
const Stack = createStackNavigator();
 
const Router = () => {
 return (
   <ThemeProvider theme={variables}>
     <NavigationContainer>
       <Stack.Navigator initialRouteName="Home">
         <Stack.Screen name="Home" component={Home} />
         <Stack.Screen name="Dashboard" component={Dashboard} />
       </Stack.Navigator>
     </NavigationContainer>
   </ThemeProvider>
 );
};
 
export default Router;

I prepared two components/views. Home is a little bit modified from the previous example - the button and style via style-components are added.

  <Button onPress={() => navigation.navigate('Dashboard')}>
       <Text>
         <FormattedMessage id="app.home.button" />
       </Text>
  </Button>

Why did I decide to use styled components? In my opinion, it fits the logic of working on components better than a standard CSS class.

Styled components

Styled components is a library that allows us to change standard CSS rules for React components and use them as functional components. Use template literals and all power of CSS including animations and keyframes objects.

Of course, we have more benefits:

  • No class name bugs
  • Simple dynamic style
  • Simple managed and deleted CSS rules
  • Automatic vendor prefixing

To summarize, we can create reusable components and if necessary overwrite existing code, add completely new flags and render extra CSS depending on the needs. You decide which solution will be the best.

In the example below I used styled components like wrapper. In the same way we can modify another component. If you want to style HTML element you have to write something like this:

import styled from 'styled-components';
 
export const Input = styled.input`
 ....
  CSS rules
 ....
`;
 
export const Paragraph = styled.p`
 ....
  CSS rules
 ....
`;

See, it is simple. But what if in the project we use TypeScript? Don't worry: styled components support TS. You can write:

export const Paragraph = styled.p<{ bold?: boolean }>`
 font-weight: ${(props) => (props.bold ? '700' : '400')};
`;

At the beginning I mentioned the flags. They are useful when you want to add more rules or isolate fragments of code.

import styled, { css } from 'styled-components';
export const Paragraph = styled.p<{ bold?: boolean; error?: boolean }>`
 font-weight: ${(props) => (props.bold ? '700' : '400')};
 
 ${({ error }) =>
   error &&
   css`
     font-color: red;
     font-size: 18px;
     text-align: center;
   `}
`;

Ok, we come back to the app and write some CSS rules to our button.

TouchableOpacity it’s a wrapper area where the user can activate some action. In this case, it is a navigation to the other view.

import styled from 'styled-components';
import { TouchableOpacity } from 'react-native';
 
export default styled(TouchableOpacity)`
 background-color: ${({ theme }) => theme.colors.violetLight};
 padding: 8px 16px;
 border-radius: 3px;
`;

Thank you for reading! I hope the article was useful for you. See you next time!

What do you think? Share your impressions!

Meet the author

Patryk
Diamond logo icon
Mail logo

Patryk Kluczak

Frontend Developer

I am JS Developer, specialize in creating stucture and implementing solution for multiplatform app.

Still have some questions?

If you have any questions, feel free to contact us. Our Business Development Team will do their best to find the solution.