{"id":104,"date":"2024-11-24T15:32:41","date_gmt":"2024-11-24T15:32:41","guid":{"rendered":"https:\/\/blog.vyomscode.com\/?p=104"},"modified":"2024-11-24T15:32:41","modified_gmt":"2024-11-24T15:32:41","slug":"creating-authentication-in-react-native-part-1-home-and-register-screens","status":"publish","type":"post","link":"https:\/\/blog.vyomscode.com\/index.php\/2024\/11\/24\/creating-authentication-in-react-native-part-1-home-and-register-screens\/","title":{"rendered":"Creating Authentication in React Native &#8211; Part 1: Home and Register Screens"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<p>Building a robust authentication system is a cornerstone of any modern mobile application. In this two-part series, we\u2019ll explore how to implement authentication in a React Native app using Expo Router and TypeScript.<\/p>\n\n\n\n<p>This first part focuses on creating the <strong>Home<\/strong> and <strong>Register<\/strong> screens and setting up the necessary navigation structure.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"1024\" src=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-1024x1024.jpg\" alt=\"\" class=\"wp-image-108\" style=\"width:371px;height:auto\" srcset=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-1024x1024.jpg 1024w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-300x300.jpg 300w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-150x150.jpg 150w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-768x768.jpg 768w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-1536x1536.jpg 1536w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/Wavy_Bus-43_Single-12-2048x2048.jpg 2048w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. <strong>Setting Up Authentication Layout<\/strong><\/h2>\n\n\n\n<p>To start, we need to define the layout for authentication screens. Modify the <code>auth\/_layout.tsx<\/code> file as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Redirect, Stack } from 'expo-router'; \n\nexport default function AuthLayout() { \n  return ( \n    &lt;Stack&gt;  \n      &lt;Stack.Screen name=\"index\" options={{ headerShown: false }} \/&gt; \n      &lt;Stack.Screen name=\"Register\" options={{ headerShown: false }} \/&gt; \n      &lt;Stack.Screen name=\"Login\" options={{ headerShown: false }} \/&gt; \n      &lt;Stack.Screen name=\"OTPVerify\" options={{ headerShown: false }} \/&gt; \n      &lt;Stack.Screen name=\"ForgetPass\" options={{ headerShown: false }} \/&gt;\n    &lt;\/Stack&gt;\n  );\n}\n<\/code><\/pre>\n\n\n\n<p>You can add additional screen definitions to the layout as needed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. <strong>Creating the Home Screen<\/strong><\/h2>\n\n\n\n<p>The <strong>Home Screen<\/strong> introduces users to the app and provides a &#8220;Get Started&#8221; button.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Code: <code>auth\/index.tsx<\/code><\/h5>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"461\" height=\"1024\" src=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.36_2be6a7e9-461x1024.jpg\" alt=\"\" class=\"wp-image-106\" style=\"width:250px;height:auto\" srcset=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.36_2be6a7e9-461x1024.jpg 461w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.36_2be6a7e9-135x300.jpg 135w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.36_2be6a7e9-691x1536.jpg 691w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.36_2be6a7e9.jpg 720w\" sizes=\"(max-width: 461px) 100vw, 461px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from 'react';\nimport { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';\nimport { useNavigation, NavigationProp } from '@react-navigation\/native';\nimport { ListAuth } from '@\/src\/types'; \nimport Logo from '..\/..\/..\/assets\/images\/icon.png';  \nimport authbg from '..\/..\/..\/assets\/images\/authbg.jpg';\nimport Colors from '@\/src\/constants\/Colors'; \n\nconst HomeScreen = () =&gt; {\n  const navigation = useNavigation&lt;NavigationProp&lt;ListAuth&gt;&gt;();\n\n  const handlePress = () =&gt; {\n    navigation.navigate('Register');   \n  }; \n\n  return (\n    &lt;View style={styles.container}&gt;\n      &lt;View style={styles.backgroundContainer}&gt;\n        &lt;Image source={authbg} style={styles.backgroundImage} \/&gt;\n      &lt;\/View&gt;\n      &lt;View style={styles.content}&gt;\n        &lt;Text style={styles.heading}&gt;Hey, Welcome to&lt;\/Text&gt;\n        &lt;Image source={Logo} style={styles.logo} \/&gt; \n        &lt;TouchableOpacity style={styles.button} onPress={handlePress}&gt;\n          &lt;Text style={styles.buttonText}&gt;Get Started \u279c&lt;\/Text&gt;\n        &lt;\/TouchableOpacity&gt;\n      &lt;\/View&gt;\n    &lt;\/View&gt;\n  );\n};\n\nconst styles = StyleSheet.create({ \n  container: {\n    flex: 1,\n    paddingTop: 80,\n    alignItems: 'center',\n    backgroundColor: 'white',\n  },\n  backgroundContainer: {\n    ...StyleSheet.absoluteFillObject,\n    zIndex: -1,\n  },\n  backgroundImage: {\n    flex: 1,\n    width: null,\n    height: null,\n  },\n  content: {\n    alignItems: 'center',\n    zIndex: 1,  \n  },\n  logo: {\n    width: 170,\n    height: 90,\n    marginBottom: 20,\n  },\n  heading: {\n    fontSize: 22,\n    fontWeight: 'bold',\n    color: Colors.blue.color,\n    marginBottom: 5,\n    fontStyle: 'italic',\n  },\n  button: {\n    backgroundColor: Colors.orange.color,\n    paddingVertical: 20,\n    paddingHorizontal: 70,\n    borderRadius: 5,\n    marginTop: 380,\n  },\n  buttonText: {\n    color: 'white',\n    fontSize: 18,\n    fontWeight: 'bold',\n  },\n});\n\nexport default HomeScreen;\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Notes:<\/h3>\n\n\n\n<ul>\n<li>Add required images (<code>authbg.jpg<\/code>, <code>icon.png<\/code>) to your assets folder.<\/li>\n\n\n\n<li><code>ListAuth<\/code> defines type safety for navigation.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. <strong>Handling Image Imports<\/strong><\/h2>\n\n\n\n<p>To handle image imports (<code>.jpg<\/code>, <code>.png<\/code>, etc.), create a file named <code>declarations.d.ts<\/code> in the <code>src<\/code> folder:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>declare module '*.jpg';\ndeclare module '*.png';\ndeclare module '*.jpeg';\ndeclare module '*.gif';\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">4. <strong>Defining Types<\/strong><\/h2>\n\n\n\n<p>Add the following to <code>src\/types.tsx<\/code> to define screen navigation types:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export type ListAuth = { \n  Home: undefined;\n  Register: undefined;\n  Login: undefined;\n  ForgetPass: undefined;\n  PasswordResetNumber: undefined; \n  OTPVerify: {\n    name: string; \n    phoneText: string;\n    password: string;\n    email: string;\n    otp: string;\n    referal: string;\n  }; \n};\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code><h2>5. <strong>Setting Up Colors<\/strong><\/h2><p>Define reusable colors in <span style=\"background-color: initial; font-family: inherit; font-size: 0.9375rem;\">src\/constants\/Colors.ts<\/span>:<\/p><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>export default {\n  light: {\n    orange: { color: '#B95900' },\n    blue: { color: '#045081' },\n    green: { color: '#037F00' },\n  },\n  dark: {\n    orange: { color: '#B95900' },\n    blue: { color: '#045081' },\n    green: { color: '#037F00' },\n  },\n};\n<\/code><\/pre>\n\n\n\n<p>Customize the colors as needed for your app theme.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. <strong>Building the Register Screen<\/strong><\/h2>\n\n\n\n<p>The <strong>Register Screen<\/strong> collects user details and sends them to the backend.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Code: <code>auth\/Register.tsx<\/code><\/h5>\n\n\n\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"461\" height=\"1024\" src=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.37_21740c1c-461x1024.jpg\" alt=\"\" class=\"wp-image-107\" style=\"width:226px;height:auto\" srcset=\"https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.37_21740c1c-461x1024.jpg 461w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.37_21740c1c-135x300.jpg 135w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.37_21740c1c-691x1536.jpg 691w, https:\/\/blog.vyomscode.com\/wp-content\/uploads\/2024\/11\/WhatsApp-Image-2024-11-24-at-20.51.37_21740c1c.jpg 720w\" sizes=\"(max-width: 461px) 100vw, 461px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react';\nimport { View, Text, StyleSheet, TextInput, Alert, TouchableOpacity } from 'react-native';\nimport { useNavigation, NavigationProp } from '@react-navigation\/native';\nimport { RootStackParamListAuth } from '@\/src\/types';\nimport Colors from '@\/src\/constants\/Colors';\n\nconst Register = () =&gt; {\n  const &#91;name, setName] = useState('');\n  const &#91;phoneText, setPhoneText] = useState('');\n  const &#91;password, setPassword] = useState('');\n  const &#91;email, setEmail] = useState('');\n  const navigation = useNavigation&lt;NavigationProp&lt;RootStackParamListAuth&gt;&gt;();\n\n  const handleRegister = () =&gt; {\n    if (!name || !phoneText || !password || !email) {\n      Alert.alert('Error', 'All fields are required');\n      return;\n    }\n\n    const formData = new FormData();\n    formData.append('action', 'register');\n    formData.append('name', name);\n    formData.append('mobile', phoneText);\n    formData.append('password', password);\n    formData.append('email', email);\n\n    fetch('https:\/\/your-api-endpoint.com\/register', {\n      method: 'POST',\n      body: formData,\n    })\n      .then(response =&gt; response.json())\n      .then(data =&gt; {\n        if (data.status === 'success') {\n          Alert.alert('Success', 'User registered successfully');\n          navigation.navigate('Login');\n        } else {\n          Alert.alert('Error', data.message || 'Failed to register user');\n        }\n      })\n      .catch(error =&gt; {\n        Alert.alert('Error', 'Failed to register. Please try again.');\n      });\n  };\n\n  return (\n    &lt;View style={styles.container}&gt;\n      &lt;Text style={styles.heading}&gt;Register&lt;\/Text&gt;\n      &lt;TextInput placeholder=\"Name\" value={name} onChangeText={setName} style={styles.input} \/&gt;\n      &lt;TextInput placeholder=\"Phone\" value={phoneText} onChangeText={setPhoneText} style={styles.input} \/&gt;\n      &lt;TextInput placeholder=\"Email\" value={email} onChangeText={setEmail} style={styles.input} \/&gt;\n      &lt;TextInput placeholder=\"Password\" value={password} onChangeText={setPassword} style={styles.input} secureTextEntry \/&gt;\n      &lt;TouchableOpacity onPress={handleRegister} style={styles.button}&gt;\n        &lt;Text style={styles.buttonText}&gt;Register&lt;\/Text&gt;\n      &lt;\/TouchableOpacity&gt;\n    &lt;\/View&gt;\n  );\n};\n\nconst styles = StyleSheet.create({\n  container: { padding: 20 },\n  heading: { fontSize: 24, marginBottom: 20 },\n  input: { borderWidth: 1, padding: 10, marginBottom: 10, borderRadius: 5 },\n  button: { backgroundColor: Colors.blue.color, padding: 15, borderRadius: 5 },\n  buttonText: { color: 'white', textAlign: 'center' },\n});\n\nexport default Register;\n<\/code><\/pre>\n\n\n\n<p>In the next part, we\u2019ll focus on creating the <strong>Login<\/strong> screen, adding OTP verification, and handling authentication states. Stay tuned! \ud83d\ude80<\/p>\n\n\n\n<p><a href=\"https:\/\/tripti.vyomscode.com\/\">Tripti<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Building a robust authentication system is a cornerstone of any modern mobile application. In this two-part series, we\u2019ll explore how to implement authentication in a React Native app [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/104"}],"collection":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=104"}],"version-history":[{"count":2,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/104\/revisions"}],"predecessor-version":[{"id":109,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/posts\/104\/revisions\/109"}],"wp:attachment":[{"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=104"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=104"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.vyomscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=104"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}