Intro to React Native
Tags: beginners, tutorial, react, javascript
Published: 2024-06-04 06:34:28

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](https://nodejs.org/en/learn/getting-started/introduction-to-nodejs) 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:

1. View: The fundamental building block for UI, similar to div in HTML.
2. Text: For displaying text.
3. Image: For displaying images.
4. TextInput: For input fields.
5. 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](https://reactnative.dev/docs/getting-started) and the [React Navigation guide](https://reactnavigation.org/docs/getting-started/).