AppDividend
Latest Code Tutorials

How To Connect React Native Application With Laravel API Tutorial

React Native Laravel Tutorial

7,467

Get real time updates directly on you device, subscribe now.

In this application tutorial, I have described How To Connect React Native Application With Laravel API Tutorial From Scratch. For this tutorial, I will show you the example in the iOS Simulator. We will use Laravel 5.6 as a backend and React Native as a front end. We connect our front-end mobile application to the backend Laravel API and display the database values on the frontend. Nothing more complicated. So you will see how we can send the Network request to the server and get the response and append that into react native components. If you have worked with React.js, then it is quite familiar to you.

Related Article: Beginners Guide To Create React Native Application

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

React Native Application With Laravel API Tutorial.

The first step will be to install a React Native application on Mac.

Step 1: Install React Native app.

Hit the following command on the terminal.

sudo npm install -g react-native-cli

Go to the directory, where you need to generate the project.

react-native init RNLaravel
cd RNLaravel

Now, run the project by typing the following command.

react-native run-ios

After some compilation, react package manager will be opened on the terminal and after that iOS device will be opened with a screen like below.

React Native Starter App

Step 2: Create required directories.

In the root of the project, make the one directory called src.  In that directory, create three folders.

  1. screens
  2. components
  3. services

Screens folder contains the screens which we need to display to the User. In our case, we will create two screens.

Components folder contains the mobile components we will use to display the data from the API.

Services folder contains network files. It is the files in which we will write the code to make a request to the server and get the response from the server.

Step 3: Create two screens.

Inside src  >>  screens folder, create the following files.

  1.  Home.js
  2. Coin.js

Home.js is the pure React Native class.

// Home.js

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export class Home extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
      </View>
    )
  }
}

export default Home;

Same do for the Coin.js file.

// Coin.js

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export class Coin extends Component {
  render() {
    return (
      <View>
        <Text>Coin Screen</Text>
      </View>
    )
  }
}

export default Coin;

Step 4: Integrate React Native Navigation.

We need to install React Navigation library to transition the app from one screen to another screen.

yarn add react-navigation

Now, after installing, go to the App.js file. We will use StackNavigator to transit from one to another screen. It is kind of routing for our application.

Related Posts
1 of 8
// App.js

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Home from './src/screens/Home';
import Coin from './src/screens/Coin';

const AppNavigator = StackNavigator({
  HomeScreen: { screen: Home },
  CoinScreen: { screen: Coin }
});

export default class App extends Component {
  render() {
    return (
      <AppNavigator />
    );
  }
}

We have included both the screen here and passed that screen into the StackNavigator function. It will handle the transition of our screens.

Step 5: Create Laravel Backend API.

Install the Laravel 5.6 by the following command.

composer create-project laravel/laravel --prefer-dist RNativeLaravel

After installing the Laravel configure the .env file. Enter your database credentials. I am using MAMP, so mine is the following. If you are using XAMPP, then your password should be empty and if AMPPS then your password should be mysql. Of course, I have created the database already in the phpMyAdmin.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=reactnative
DB_USERNAME=root
DB_PASSWORD=root

We are simply building an application, in which we just need to send the data in the JSON format to the client and in our case, it is react native. We are sending the crypto coins JSON object which contains main fields like coin name and price. So let us create the migration, model and controller file for our Laravel application.

Create the migration, model, and controller file.

Go to your Laravel root and hit the following command.

php artisan make:model Coin -m

It will create both Migration and Model file. In the migration file, add the following code.

// create_coins_table

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('coins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

Type the following command to migrate this schema into the database. So three tables will be created.

php artisan serve

Now, create the controller file by the following command.

php artisan make:controller CoinController

Code the index function inside that file.

// CoinController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Coin;

class CoinController extends Controller
{
    public function index()
    {
        $coins = Coin::all();

        return response()->json($coins);
    }
}

Above code just fetch all the data as a collection and then return an array of coins as a json response.

Right now, we do not have any coin the database. So for this example, we need to fill it manually because we are not writing any screen that can store the details of the coins. So you need to fill that out manually. I will write full CRUD application later in this blog.

MySQL Tutorial With React Native App

I have inserted only two values as this is just basic showcase tutorial. So we have already written the code that fetches this data from the database and returns this data as a JSON response. 

Write the routes in the api.php file.

Go to the routes  >> api.php file and add the following route in it.

// web.php

Route::get('coins', 'CoinController@index');

Now, start the Laravel development server by the following command.

php artisan serve

It will open the server at the port 8000.

You can access our Laravel API at this route: http://localhost:8000/api/coins

Step 6: Use fetch API of React Native to send the network request.

We need to display the coins data into the Coin screen. We have created the folder called services. So in that folder, we will create a file called FetchCoins.js. Write the following code in it.

// FetchCoins.js

const URI = 'http://localhost:8000';

export default {
    async fetchCoins() {
        try {
                let response = await fetch(URI + '/api/coins');
                let responseJsonData = await response.json();
                return responseJsonData;
            }
        catch(e) {
            console.log(e)
        }
    }
}

We have used fetch api provided by React Native to send the network request like GET and POST.

Also, we have used ES7 feature async/await feature. It is quite useful in Asynchronous tasks. 

Now, we will import FetchCoins.js file inside Coin.js file. I am writing the whole file.

// Coin.js

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import ajax from '../services/FetchCoins';
import CoinList from '../components/CoinList';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#B6A6BB',
  }
})

export class Coin extends Component {

  state = {
    coins: []
  }

  async componentDidMount() {
    const coins = await ajax.fetchCoins();
    this.setState({coins});
  }

  render() {
    return (
      <View style={styles.container}>
      {
        this.state.coins.length > 0
        ? <CoinList coins={this.state.coins} />
        : <Text>No coins</Text>
      }
      </View>
    )
  }
}

export default Coin;

In this file basically, what I did is that first I have used componentDidMount lifecycle method for fetching the data from the server. We are using async/await for the network request. So I have written async componentDidMount method. After fetching the data, I am changing the state of coins with the filled array data and pass that array to the new component that is a CoinList.js file. We need to create that component. So let us create that component inside src >> components folder.

// CoinList.js

import React, { Component } from 'react';
import {  View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';

export default class CoinList extends Component {

  static propTypes = {
      coins: PropTypes.array.isRequired
  }; 
  render() {
    return (
      <View style={styles.coinsList}>
        {this.props.coins.map((coin) => {
            return (
                <View key={coin.id}>
                    <Text style={styles.cointext}>{coin.name} | { coin.price }</Text>
                </View>
            )
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
    coinsList: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-around',
    },
    cointext: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
    }
});

CoinList.js file receives the data as a component. So I have used the map function to display the data into formatted text.  If you have worked with React.js before then it is quite familiar to you. Of course here the design style is different then React.js web components. Now, reload our application. You will see something like below screen.

Laravel React Native Tutorial

Okay, now press the Coins button. You will see the screen with our two coins data.

React Native Fetch Tutorial

So this is how you can perform a network request in the React Native mobile application. It is the simple example of Fetch React Native API. Finally,  How To Connect React Native Application With Laravel API Tutorial is over. Thanks for taking this article.

 

11 Comments
  1. How To Connect React Native Application With Laravel API Tutorial - ReactJS News

    […] How To Connect React Native Application With Laravel API Tutorial […]

  2. Jephte says

    Hi Krunal, Thank you on your tutorial. Just one thing, I received this error message “TypeError: ‘undefined’ is not an object (evaluating ‘this.state.coins.length’)”. I were able to display the JSON of table Coins in the browser but not able to receive them in React Native.

    1. Krunal says

      I guess you did not receive the coins from the Laravel server. Check your URL to send a network request.

      1. Sankalp says

        no it sill showing an error please suggest proper solution

        1. Krunal says

          Please show me your error here!!

          1. Sankalp says

            Like you said earlier it seems like I cant receive the coins from laravel server ,the underlying problem is that network request failed on fetch written in fetchCoin.js. I tried many solutions available on the net: changing the url to your Ip , app even has permissions to access internet but nothing seems to work. All the solutions on the net are for ios. Json table gets displayed on browser but on the app. please help

  3. Abdel says

    Hi Krunal thanks for your tutorial!
    When I try to access API endpoint I get network request failed error!!

  4. Marcello says

    Hi Krunal, I am using your article to get my head around React Native and Laravel forthe first time. I am using MAMP on Mac. Should RNLaravel be placed in MAMP/htdocs/RNLaravele or MAMP/RNLaravel?
    Also should I place my project folders in MAMP/htdocs/coins/src or MAMP/htdocs/RNLaravel/coins/src?
    Thanks!

    1. Krunal says

      It should be placed inside MAMP/htdocs/RNLaravel, or you can put wherever you want, does not matter, you can use laravel’s dev server by typing: php artisan serve in the root of your laravel project.

  5. Rathavithey says

    Hii Krunal Says,

    Can you help me after i run react native, the result show ‘No Coins’, but for url is show data,

    can you help me to check ?

  6. Rathavithey says

    Hii,

    For url = http://localhost:8000

    had you test it with React Native can support with api url in localhost ?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.