Intro to React Native
AJ
Posted on June 4, 2024
This blog is a comprehensive guide for beginners who are looking to use react software for their wants and needs. First, before we dive into the code, let's complete a quick history lesson about what react is exactly.
What is React Native?
React Native was developed by Facebook as an open-source framework that allows developers to create cross-platform apps using JavaScript and React. This software has emerged as one of the most popular frameworks for building mobile applications and it enables developers to use the same codebase to create applications for both iOS and Android. Unlike other cross-platform frameworks that use WebView, React Native directly translates components into native ones, resulting in better performance and a more native feel.
Environment Set Up
Now before we start, you need to set up your development environment. Ensure you have Node.js installed, then install the React Native CLI by running:
npm install -g react-native-cli
You can then create a new project with:
react-native init MyNewProject
cd MyNewProject
Congratulations, you've successfully installed React and created your first project with the framework!
Say Hello
As usual a quick and easy way to familiarize yourself with a new environment is to start with a hello function. So now open the App.js file and replace its contents with the following code:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, World!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
export default App;
Explanation
1. Imports:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
Here, we're importing the core components from React and React Native. View is similar to div in HTML, Text is used to display text, and StyleSheet is used for styling.
2. App Component:
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, World!</Text>
</View>
);
};
The App component returns a View component that contains a Text component. The Text component displays "Hello, World!" on the screen.
3. Styling:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
The StyleSheet.create
method is used to create styles for the components instead of CSS. The container style centers the content both vertically and horizontally, and the text style sets the font size and text alignment.
Core Components
React Native offers several core components for building user interfaces. Here are a few essential ones:
- View: The fundamental building block for UI, similar to div in HTML.
- Text: For displaying text.
- Image: For displaying images.
- TextInput: For input fields.
- Button: For clickable buttons.
Here is an example of using some of the core components:
import React, { useState } from 'react';
import { View, Text, TextInput, Button, Image, StyleSheet } from 'react-native';
const App = () => {
const [name, setName] = useState('');
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to React Native!</Text>
<TextInput
style={styles.input}
placeholder="Enter your name"
onChangeText={text => setName(text)}
value={name}
/>
<Button title="Greet" onPress={() => alert(`Hello, ${name}!`)} />
<Image
style={styles.image}
source={{ uri: 'https://reactnative.dev/img/tiny_logo.png' }}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 24,
marginBottom: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 20,
padding: 10,
width: '80%',
},
image: {
width: 100,
height: 100,
},
});
export default App;
Explanation: Part 2
1. State Management
const [name, setName] = useState('');
We use the useState
hook to create a state variable name and a function setName
to update it. Initially, name is an empty string.
2. Text Component
<Text style={styles.text}>Welcome to React Native!</Text>
Displays a welcome message. The style prop applies the text style defined in the StyleSheet
.
3. TextInput Component
<TextInput
style={styles.input}
placeholder="Enter your name"
onChangeText={text => setName(text)}
value={name}
/>
Creates an input field. The onChangeText prop updates the name state with the text entered by the user. The value prop sets the current value of the input to name.
4. Button Component
<Button title="Greet" onPress={() => alert(`Hello, ${name}!`)} />
Displays a button that, when pressed, shows an alert with the message "Hello, {name}!".
5. Image Component
<Image
style={styles.image}
source={{ uri: 'https://reactnative.dev/img/tiny_logo.png' }}
/>
Displays an image from a URL. The source prop takes an object with a uri key pointing to the image URL.
6. Styling (Never forget this part.)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 24,
marginBottom: 20,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 20,
padding: 10,
width: '80%',
},
image: {
width: 100,
height: 100,
},
});
The container style centers the content, the text style sets the font size and margin, the input style defines the input field's dimensions and appearance, and the image style sets the image size.
Navigation
Navigation in React Native is handled by libraries like React Navigation. To get started, install React Navigation:
npm install @react-navigation/native
npm install @react-navigation/stack
npm install react-native-screens react-native-safe-area-context
Here's a basic example of navigation:
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { View, Text, Button } from 'react-native';
const HomeScreen = ({ navigation }) => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
};
const DetailsScreen = () => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Details Screen</Text>
</View>
);
};
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
Explantion
1. Navigation Components
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
We import the NavigationContainer
and createStackNavigator
from React Navigation. The NavigationContainer
manages our app's navigation state, while createStackNavigator
helps us create a stack-based navigation system.
2. HomeScreen Component
const HomeScreen = ({ navigation }) => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
};
This component displays a "Home Screen" message and a button. When the button is pressed, it navigates to the "Details" screen using the navigate method from the navigation prop.
3. DetailsScreen Component
const DetailsScreen = () => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Details Screen</Text>
</View>
);
};
This component displays a "Details Screen" message.
4. Stack Navigator
const Stack = createStackNavigator();
Here we create a stack navigator instance for our code.
5. App Component
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
The App component sets up the navigation container and the stack navigator. The initialRouteName
prop specifies the initial screen to display. Each Stack.Screen
component defines a route, associating a name with a component.
In Conclusion
React Native simplifies mobile app development by allowing developers to use a single codebase for both iOS and Android. With core components, easy setup, and extensive documentation, it's a great choice for building high-performance mobile applications.
For further reading, check out the official React Native documentation and the React Navigation guide.
Posted on June 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 18, 2023