October 3, 2024 · 6 min read · 576 views
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.
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.
User Authentication: Includes login, registration, and password reset functionality.
Profile Management: Allow users to view and update their profiles.
Toast Notifications: Provide user feedback with sleek toast notifications.
Form Error Handling: Robust error handling for form submissions.
UI Components: A set of pre-built, customizable UI components.
TypeScript Support: Enjoy the benefits of static typing for a more maintainable codebase.
TailwindCSS Integration: Use the power of TailwindCSS with TWRNC for styling.
The starter kit includes a modern tech stack, such as:
TanStack Query for data fetching and caching
React Hook Form for form management
Expo Icons for a wide range of icons
Before we dive into the code, let's set up our development environment. Make sure you have the following installed:
Node.js (LTS version)
npm or Yarn
Expo CLI (npm install -g expo-cli
)
Let's begin by setting up the Expo Starter Kit:
Clone the repository:
git clone https://github.com/lucky-media/react-native-breeze.git
cd expo-starter-kit
Install dependencies:
npm install
Configure your environment variables: Open the constants/config.ts
file and update the APP_URL
to point to your Laravel backend.
Start the development server:
npm run start
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.
One of the core features of this starter kit is its robust authentication system. Let's explore how it works:
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.
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.
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.
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.
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:
Login: POST /api/login
Register: POST /api/register
Forgot Password: POST /api/forgot-password
Get User: GET /api/user
Update User: POST /api/user
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.
The starter kit includes several custom hooks and utilities that make development easier:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
Technologies:
Related Posts
Stay up to date
Be updated with all news, products and tips we share!