Build Your First React Native App
Join the DZone community and get the full member experience.
Join For FreeInterested in learning React Native? Let’s build your first React Native, a simple app displaying a list of countries, fetched from a REST API with a network request. This React Native tutorial is aimed at introducing React Native, giving you the basis of what you need to know before building a real React Native application. After that, we proceed to helping you build your first real React Native app. By the end of this article you will build a React Native app that can run on both iOS and Android devices.
React Native is a cross-platform development library built on top of React by Facebook, for mobile development platforms. React Native was developed in 2013 as a hackthon project inside Facebook and was later released for public use in 2015. It gained huge popularity in the developer community, and multiple tech companies adopted it as a mobile development solution because React Native apps share a single codebase for both iOS and Android and could hardly be distinguished from truly native apps. According to the React Native website:
In 2018, React Native had the 2nd highest number of contributors for any repository in GitHub. Today, React Native is supported by contributions from individuals and companies around the world, including Expo and Microsoft.
Before we go ahead and build our first React Native app, I’m going to show you the pros and cons of React Native and and more details on what it actually is.
What Is React Native?
- React Native is a hybrid mobile development library.
- React Native apps are written in JSX and Javascript and compiled into native code.
- React Native apps contain 85-90% shared Javascript and JSX code
What is React Native not?
- React Native is not a webview
- React Native is not React
- React Native is not PWA
- React Native as of this writing supports web development using React Native for Web.
Why should you adopt/learn React Native?
- Targets multiple platforms (iOS, Android, Web, TVOS) with the same codebase and effort
- Has a large and growing community that is there to provide adequate support
- Has native support meaning that you can customize the native code to suit your use-case/business logic
- Requires knowledge of JavaScript. JavaScript is a language in high popular demand and learning it will pay off immensely
- Has a feature which I personally refer to as the sweet spot: Fast Refresh (Hot Reloading)
React Native Drawbacks?
React Native has some drawbacks too, but the developers of the library are consistently trying to improve them as the community grows:
- While the codebase is mostly shared among various platform, knowledge of native development is sometimes required in developing more advanced React Native projects
- Despite the fact that most React Native apps look the same in appearance to native apps React Native seems to lack the smooth navigation achieved by native apps.
- React Native developers agree that React Native style of error reporting is not the best out there but they cope with it over time.
Build Your First React Native App
Let’s build a React Native app to display a simple list of countries. The app will contain only one screen, and we are going to keep its functionality and styling to a minimum since the purpose of this tutorial is to help you set up your React Native developer environment and dip your toes into the React Native programming language.
In this React Native tutorial, we are going to use Expo in order to build your first React Native application. Expo is a powerful tool for those how are beginners in the React Native world since it lets you run and preview React Native apps on your devices easily.
1. Install Expo
Follow the official documentation on how to install Expo. Once you’ve installed it, come back to this tutorial and follow the next steps in order to build your first React Native app.
2. Create a New React Native App
xxxxxxxxxx
expo init firstapp
Select the ‘blank‘ project
Select ‘Y‘ to work with yarn.
xxxxxxxxxx
Yarn v1.19.2 found. Use Yarn to install dependencies? (Y/n)
Once you click Yes, Expo will work its magic and create all the necessary files for you. You can take a look at the directory structure to get an idea of what is going on in the project.
3. Run Your First React Native App
Run the following commands to start your newly created React Native app:
xxxxxxxxxx
cd firstapp
yarn start
At this point, if you set up Expo properly at the previous steps, the new React Native project should have loaded successfully and you should be able to see the app as in the following screenshot:
There you have it, the very first React Native application that you’ve build. By default it says ‘Open up App.js to start working on your app‘ and I agree that it’s not the best welcome message Expo could offer but we’re going to go ahead and do as they say. Let’s open App.js file, which looks like this:
xxxxxxxxxx
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Now let me give a concise summary of what’s going on before we move on.
- The styles variable contains various style dicts of the components
- The Function App is a React Native Functional Component, the default one that renders what we currently see on our screen and above are import statements that import components to be used and composed to create our parent component App.
4. Add List of Countries
Let’s move on and rewrite this dummy screen with our own UI. As we mentioned before, we are going to display a list of countries. For this, we need to implement the following:
xxxxxxxxxx
import React from 'react';
import { StyleSheet, Text, FlatList } from 'react-native';
export default function App() {
const countriesData = [{"name":"Afghanistan"},{"name":"Åland Islands"},{"name":"Albania"},{"name":"Algeria"}]
return (
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text style={styles.text}>{item.name}</Text>}
/>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
},
text: {
fontSize: 20,
margin: 10
},
});
As you can see, we have updated our App.js and added a few things:
- A Flatlist to display the list of countries
- A dummy dataset to display to be displayed on the list
- We updated the style object to contain the style for our text
Run your app if you haven’t started it already, and you should be seeing this:
We now have something to work with. But the data is static and we would like a longer dynamic list, that can change and we need those changes to be reflected in the UI. So we need the UI to be “reactive” to the changes in the data model. This is the core concept of React, and therefore React Native. So we need to introduce the State concept.
A React Native component holds data in its state, and whenever the state changes, the UI is re-rendered to reflect those changes. Let’s add a state variable, named countriesData which will store the dynamic list of countries displayed on the screen.
- const [countriesData, setCountriesData] = useState([])
The useState is called a “hook” in React Native. According to official React documentation on hooks
A Hook is a special function that lets you “hook into” React features
We just declared a state for our app countriesData with default value as an empty array [] and a function setCountriesData to update the value of countriesData. For example, calling setCountriesData([1,2,3,]) will update the value of countriesData to [1,2,3,].
Another important hook useEffect is going to be applied in the following code snippet. Simply put, any code written inside the useEffect runs when the component is mounted.
xxxxxxxxxx
import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, FlatList } from 'react-native';
export default function App() {
const [countriesData, setCountriesData] = useState([])
function fetchCountriesData() {
fetch('https://restcountries.eu/rest/v2/region/africa?fields=name')
.then((response) => response.json())
.then((json) => setCountriesData(json))
.catch((error) => console.error(error))
}
useEffect(()=> {
fetchCountriesData();
})
return (
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text style={styles.text}>{item.name}</Text>}
/>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
},
text: {
fontSize: 20,
margin: 10
},
});
Please don’t be scared of what’s going on. We are using the fetch API to retrieve countries data from an API endpoint and display a list of African countries. The fetch API is how you make network requests in React Native. As you can notice, we’ve used a free API endpoint, exposed on the restcountries.eu website. This returns a JSON object, parsed in the then() clause of the fetch method. Once parsed successfully, we update the countriesData state variable with the new list of country, newly retrieved. As a result of updating the state object, the UI also gets re-rendered and we can see the countries on the screen:
5. Styling Your First React Native App
Let’s now focus on making the design of the app slightly better, since we already have the core functionality in place. We are going to focus on styling the app and our focus is on the styles dictionary.
xxxxxxxxxx
import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, FlatList, Pressable, Alert } from 'react-native';
import { StatusBar } from 'expo-status-bar';
export default function App() {
const [countriesData, setCountriesData] = useState([])
function fetchCountriesData() {
fetch('https://restcountries.eu/rest/v2/region/africa?fields=name;capital')
.then((response) => response.json())
.then((json) => setCountriesData(json))
.catch((error) => console.error(error))
}
useEffect(()=> {
fetchCountriesData();
})
return (
<>
<StatusBar style='light'/>
<FlatList
data={countriesData}
contentContainerStyle={styles.container}
keyExtractor={item => item.name}
renderItem={({item})=> <Text onPress={() => {Alert.alert(`The Capital of ${item.name} is ${item.capital}`)}} style={styles.text}>{item.name}</Text>}
/>
</>
);
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
backgroundColor: '#483D8B'
},
text: {
fontSize: 18,
margin: 5,
color: '#fff'
},
});
As you can see, we’ve changed the color of the background to purple, by providing the backgroundColor attribute with ‘#483D8B’ hex code.
While the syntax is very similar to CSS, it is slightly different. But the core concepts are the same, so if you already know CSS, learning how to style React Native apps will be extremely easy. Especially if you are already familiar with flexbox layout.
Conclusion
We saw what are the biggest sell points for using React Native in your mobile development process, and how easy it is to create apps for both iOS and Android.
We’ve set up Expo, which is an amazing tool for beginners who are new to the React Native world. We then leveraged Expo to create our first React Native project.
After that, we learned about functional components, hooks and state. We’ve used the fetch API to retrieve data via a network request, and we styled the visual components by modifying the stylesheet.
Congratulations! You were able to build a React Native app. Now it’s time to learn more advanced concepts, in order to add more complex functionalities and develop fully functional mobile apps, that you can publish to the App Store and Google Play Store. Check out this list of the best React Native resources to learn more about React Native and dive into the next level.
Published at DZone with permission of krissanawatt kaewsanmunag. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments