React Native Breeze: A Laravel Inspired Starter Kit for Mobile App Development

lokman musliu
Lokman Musliu

October 3, 2024 · 6 min read · 576 views

Laravel React Native Expo

Are you looking to create a powerful, cross-platform mobile application that seamlessly integrates with a Laravel backend? Look no further! In this blog post, we'll explore how to use our React Native Breeze starter kit designed to work harmoniously with Laravel, while maintaining the flexibility to adapt to other backend technologies.

Introduction to the React Native Breeze

This Expo-based mobile application starter kit draws inspiration from Laravel Breeze, providing a smooth developer experience and rich features. Let's see what makes this starter kit special and how to use it for your next project.

Key Features

  1. User Authentication: Includes login, registration, and password reset functionality.

  2. Profile Management: Allow users to view and update their profiles.

  3. Toast Notifications: Provide user feedback with sleek toast notifications.

  4. Form Error Handling: Robust error handling for form submissions.

  5. UI Components: A set of pre-built, customizable UI components.

  6. TypeScript Support: Enjoy the benefits of static typing for a more maintainable codebase.

  7. TailwindCSS Integration: Use the power of TailwindCSS with TWRNC for styling.

React Native Breeze tech stack

Tech Stack

The starter kit includes a modern tech stack, such as:

Setting Up Your Development Environment

Before we dive into the code, let's set up our development environment. Make sure you have the following installed:

  1. Node.js (LTS version)

  2. npm or Yarn

  3. Expo CLI (npm install -g expo-cli)

Getting Started With React Native Breeze

Let's begin by setting up the Expo Starter Kit:

  1. Clone the repository:

    git clone https://github.com/lucky-media/react-native-breeze.git

    cd expo-starter-kit

  2. Install dependencies:

    npm install

  3. Configure your environment variables: Open the constants/config.ts file and update the APP_URL to point to your Laravel backend.

  4. Start the development server:

    npm run start

Understanding the Project Structure

The starter kit follows a well-organized structure. Here are some key directories and files:

  • app/: Contains the main application screens and navigation setup.

  • components/: Reusable UI components.

  • context/: React context providers for global state management.

  • features/: Feature-specific logic and API calls.

  • hooks/: Custom React hooks.

  • utils/: Utility functions and helpers.

Authentication Flow

One of the core features of this starter kit is its robust authentication system. Let's explore how it works:

Login

The login functionality is implemented in the app/(auth)/login.tsx file. It uses React Hook Form for form management and the useLoginMutation hook for handling the API call:

export default function Login() {
  const userLogin = useLoginMutation();
  const { setSession } = useSession();
  const { showToast } = useToast();

  const {
    control,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm<LoginUser>({
    defaultValues: {
      email: '',
      password: '',
    },
  });

  const onSubmit: SubmitHandler<LoginUser> = async (data: LoginUser) => {
    userLogin.mutate(data, {
      onSuccess: ({ token }: Session) => {
        setSession({ token });

        router.push('/');
      },
      onError: async (error) => {
        await handleApiErrors({ error, setError, showToast });
      },
    });
  };
}

This code snippet demonstrates how the login form is set up and how it handles form submission. The useLoginMutation hook is responsible for making the API call to the Laravel backend.

Registration

Similar to the login process, user registration is handled in the app/(auth)/register.tsx file. It follows a similar pattern, using React Hook Form and a custom useRegisterMutation hook.

Password Reset

The starter kit also includes a password reset feature, implemented in app/(auth)/forgot-password.tsx. This allows users to request a password reset link via email.

Profile Management

Once a user is authenticated, they can view and update their profile. This functionality is implemented in the app/(app)/profile.tsx file:

export default function Profile() {
  const { data: user } = useUserQuery();
  const { showToast } = useToast();
  const queryClient = useQueryClient();

  const {
    control,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm<UserProfile>({
    defaultValues: {
      name: user?.name,
      password: null,
      password_confirmation: null,
    },
  });

  const userUpdate = useUpdateUserProfileMutation();

  const onSubmit: SubmitHandler<UserProfile> = async (data: UserProfile) => {
    userUpdate.mutate(data, {
      onError: async (error) => {
        await handleApiErrors({ error, setError, showToast });
      },
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['user'] });
        showToast({
          type: 'success',
          message: 'User updated successfully',
          duration: 1000,
        });
      },
    });
 };
}

This code snippet shows how the profile update form is set up and how it handles form submission. The useUpdateUserProfileMutation hook is used to send the updated profile data to the Laravel backend.

Laravel best PHP framework

Integrating with Laravel Backend

To integrate this Expo starter kit with your Laravel backend, you'll need to ensure your Laravel API endpoints match the expected routes. Here's a quick overview of the main endpoints used:

  1. Login: POST /api/login

  2. Register: POST /api/register

  3. Forgot Password: POST /api/forgot-password

  4. Get User: GET /api/user

  5. Update User: POST /api/user

  6. Logout: POST /api/logout

Make sure your Laravel routes and controllers are set up to handle these requests. You can use Laravel Sanctum for API authentication, which works well with this starter kit.

Custom Hooks and Utilities

The starter kit includes several custom hooks and utilities that make development easier:

useStorageState

This custom hook (hooks/useStorageState.ts) provides a way to persist state in secure storage:

export function useStorageState<T>(key: string): UseStateHook<T> {
  // Public
  const [state, setState] = useAsyncState<T>();

  // Get
  useEffect(() => {
    getStorageItemAsync<T>(key).then((value) => {
      setState(value);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [key]);

  // Set
  const setValue = useCallback(
    (value: T | null) => {
      setState(value);
      setStorageItemAsync(key, value);
    },
    [key],
  );

  return [state, setValue];
}

This hook is particularly useful for storing sensitive information like authentication tokens.

handleApiErrors

The handleApiErrors utility function (utils/helpers.ts) provides a centralized way to handle API errors:

export async function handleApiErrors<T extends FieldValues>({
  error,
  setError,
  showToast,
}: {
  error: any;
  setError: UseFormSetError<T>;
  showToast: (props: ToastProps) => void;
}): Promise<void> {
  if (error.name === 'HTTPError' && error.response.status === 422) {
    const errors = await (error as any).response.json();

    Object.keys(errors).forEach((field) => {
      // Join error messages on one single string
      const errorMessage = Array.isArray(errors[field])
        ? errors[field].join(' ')
        : errors[field];

      setError(field as Path<T>, {
        type: 'manual',
        message: errorMessage as string,
      });
    });
  } else {
    // Uncomment to see the full error object
    // console.log(JSON.stringify(error, null, 2));
    showToast({
      type: 'error',
      message: 'Something went wrong',
    });
  }
}

This function handles form validation errors from the backend and displays toast notifications for other types of errors.

Styling with TailwindCSS

The starter kit uses TailwindCSS via the TWRNC library for styling. This allows you to use Tailwind classes directly in your React Native components. For example:

import { Ionicons } from '@expo/vector-icons';
import type { StyleProp, ViewStyle } from 'react-native';
import { Pressable } from 'react-native';
import tw from 'twrnc';

type CheckboxProps = {
  onChange: (newValue: boolean) => void;
  checked: boolean;
  style?: StyleProp<ViewStyle>;
};

export const Checkbox = ({ onChange, checked, style }: CheckboxProps) => {
  const handleToggle = () => {
    onChange(!checked);
  };

  return (
    <Pressable
      style={[
        tw`flex items-center justify-center w-8 h-8 bg-neutral-50 rounded-md border border-neutral-300`,
        style,
      ]}
      onPress={handleToggle}
      role="checkbox"
    >
      {checked ? (
        <Ionicons name="checkmark" style={tw`text-neutral-950 text-2xl`} />
      ) : null}
    </Pressable>
  );
};

This Checkbox component demonstrates how Tailwind classes are applied using the tw function from TWRNC.

React native logo illustration

Conclusion

This Expo Starter Kit provides a solid foundation for building cross-platform mobile applications that integrate seamlessly with Laravel backends. It offers a rich set of features, including authentication, profile management, and customizable UI components, all while leveraging modern technologies like TypeScript, React Query, and Tailwind CSS.

By using this starter kit, you can significantly reduce development time and focus on building your app's unique features. Remember to customize the API endpoints to match your Laravel backend, and you'll be well on your way to creating a powerful, user-friendly mobile application.

FAQ

How does the React Native Breeze starter kit ensure code maintainability and scalability?

The starter kit is built with TypeScript, which provides static typing to catch errors early and improve code quality. The modular project structure, with clearly defined directories for components, hooks, and utilities, promotes scalability and maintainability, making it easier to add new features or modify existing ones without disrupting the codebase.

What security features are included in the React Native Breeze starter kit?

Security is a priority in the React Native Breeze starter kit. It includes secure storage for sensitive data through custom hooks like useStorageState, and it recommends using Laravel Sanctum for API authentication, which provides robust security measures for protecting user data and API endpoints.

Can I customize the UI components provided in the starter kit?

Yes, the UI components included in the React Native Breeze starter kit are fully customizable. The integration with TailwindCSS via TWRNC allows you to easily adjust styles using Tailwind classes, enabling you to create a unique look and feel for your application that aligns with your brand identity.

What are the benefits of using Expo with the React Native Breeze starter kit?

Expo simplifies the development process by providing a powerful set of tools for building, deploying, and testing React Native applications. It offers features like over-the-air updates, easy setup for push notifications, and access to a wide range of APIs, which enhance the development experience and reduce time to market.

How does the starter kit facilitate cross-platform development?

The React Native Breeze starter kit is inherently designed for cross-platform compatibility, leveraging React Native's ability to write code once and deploy it across multiple platforms. This ensures consistent functionality and user experience on both iOS and Android devices, reducing development overhead and time.


Bring Your Ideas to Life 🚀

If you need help with a React project let's get in touch.

Lucky Media is proud to be recognized as a Top Next.js Development Agency

lokman musliu
Lokman Musliu

Founder and CEO of Lucky Media

Technologies:

React
React Native
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!