Blogs
Integrations

Extend Locofy Generated React Code with Firebase Auth

Protect routes in your React projects generated by Locofy.ai using Firebase’s authentication service.

Goal: Enable users to sign up and log in either via email or  Google provider in React projects using Firebase & Locofy.ai.

This guide will take you step-by-step through the process of converting your Figma designs into React code using Locofy.ai and then extending it and adding user authentication.

Prerequisites:

  1. You will need your design ready in Figma.
  2. You will need a Locofy.ai account and have the plugin up and running on your Figma file.
  3. Your Locofy project must be configured to use React.

Turn your designs into React code with Locofy.ai

This is the design file that we’ll be using in this guide. It has 3 pages – a homepage, a login page, and a dashboard.

image of the figma file design
  1. The first step is to tag our designs. Tagging allows us to turn our designs into working components, for example, buttons, dropdowns, inputs, and more. 

    You can also work with popular UI libraries such as Material and Bootstrap by tagging your elements.

    For this app, you’ll notice items such as:

    1. Buttons
    2. Images
    3. Text
  2. Now you can make your designs responsive by configuring the styles in the Styles & Layouts tab.

    Select your components that need to be responsive and on the Locofy plugin, under the Styles & Layouts tab, you will find different media queries & states. Select the breakpoint you want to make your design responsive to and then change the styles and layout accordingly.

    You can also use auto layout for your designs for responsiveness and use the Locofy plugin to take care of layouts on different screen sizes.

  3. You can trigger actions to build fully featured apps and websites. You can head over to the ‘Actions’ tab and assign actions for click events.

    You can scroll into view and open popups and URLs amongst other actions.

    Image of the actions tab in Locofy plugin
  4. Now that our designs are tagged correctly and responsive, we can preview them.

    To preview your design, select the frame or layer that you want to view, and click the “Preview” button.

    Image of the preview button

    Once you are satisfied with your preview, you can sync your designs to Locofy Builder to add more advanced settings, share your live prototype, and export code.

  5. Click the “View Code” button at the bottom left corner of the plugin & select the frames. In our case, we’ll be syncing both frames.

    Once the sync is complete, click on “View code in the Builder”.

  6. You can turn code generated by Locofy into components inside the Locofy Builder. This allows you to easily extend and reuse the code.

    Image of the components settings inside the Locofy Builder

    In our app, we are using a header section on all the 3 pages therefore we can turn it into a component. You can quickly add props as well using the Locofy builder.

  7. Once the prototype matches the product vision, you can view the live responsive prototype that looks and feels like your end product. Then you can export the code.

    Image of the export screen

    Since only components are needed, you can choose the “Components” export option. Make sure to select all the components you need and the correct framework and project settings. Once done, you can download your code in a Zip File by hitting the “Download Zip File” button in the bottom right corner.

Exported Code Overview

After extracting the zip file you downloaded, you can see how the component and page files are structured.

Image of the folder structure

Getting Started with Firebase Project

  1. Log into the Firebase console by clicking the ‘Go to console’ present in the top right corner.

  2. Now you need to create & name a new project by clicking the ‘Add project’. Click on ‘Continue’ once done.

    Image of the Firebase project screen
  3. You will be prompted to enable Google Analytics for your project. This doesn’t affect the authentication service so enabling Analytics is entirely optional.

  4. It can take a few seconds to create and initialize your project. Once the process is finished, you will see your project dashboard.

    Image of Firebase project page.
  5. Since you are adding authentication to a React project, you need to click on the ‘Web’ icon. This will open a screen asking you to register a web app.

  6. Add an app name and proceed to see details on how to set up Firebase SDK in your React project as well as a snippet of code that initializes your Firebase app and provides it with an API key, project ID, and other values that Firebase needs to establish secure access to your account.

    Image of the Firebase web app configuration
  7. Copy the code and create a file called ‘firebase.js’ in the root of your ‘src’ folder inside your React project. Paste the code in the file.

  8. Now you need to install some libraries that make interacting with Firebase easy. 

    The first package is the official Firebase SDK that allows you to quickly authenticate your app as well as access all the features provided by Firebase.

    The second package improves the developer experience of working with Firebase by providing pre-configured React hooks that makes performing Firebase operations simple.

Configuring Authentication

  1. Open the ‘firebase.js’ file in a code editor of your choice.

  2. Firebase provides us with a set of functions that we can import and use. In this tutorial, we’ll be covering how users can sign up with an email & password, login, and also sign out. Therefore, we need to import the relevant functions in our ‘firebase.js’ file.

  3. Now go back to your Firebase project dashboard and click on "Authentication" & then click on "Get started".

    Image of different services offered by Firebase
  4. You will be presented with a bunch of sign-in providers. To get started quickly, select ‘Email/Password’. You can enable other providers later as well.

  5. Now we need an auth instance of our Firebase web app. To do so, use the following code:

  6. Now we can start working with the functions we imported earlier in step 2. For starters, we want to be able to register our users.

    For this, we’ll be using "createUserWithEmailAndPassword" function. Let’s create a new function that will allow us to add more logic.

    Here we create an async function that accepts email and password as arguments and we wrap the Firebase function in a try-catch block to handle unexpected errors. 

    We are passing the auth instance as well as the email and password to the  "createUserWithEmailAndPassword" function and storing the response in the "res" constant. We then access the ‘user’ property and log it to our console.

    If there are any issues, the function will throw an error and we catch it and show an alert message and log it into the console.

  7. Similarly, we can now create a "logInWithEmailAndPassword" function.

    In this function, we are again using the try-catch block and using the "signInWithEmailAndPassword" Firebase function and passing our auth instance, email, and password to it.

    However, you will notice that in our catch block, we are checking if the error code is "auth/user-not-found", i.e if the user is signing up for the first time, and based on this we are using the function we created in step 6 to create a new user account and authenticating our user.

  8. Finally, we also need to provide users with an option to sign out. This is made easy with the “signOut” function provided by Firebase.

  9. Now you need to export all these functions so we can import & use them in relevant React pages. After following the steps, your Firebase file will look this:

Authenticating Users & Protecting Routes

  1. The first thing you need to authenticate users is a form that accepts an email & password.

  2. Create a button that the users can click to submit the data & add an onClick event listener that will trigger a function.

  3. Now we need to import the functions we created in our “firebase.js” file.

    Specifically, the auth instance and “logInWithEmailAndPassword” functions as well as the “useAuthState” hook from the "react-firebase-hooks/auth" package.

  4. Now we can create the "onButtonClick" function that we created in step 2.

    Here we are using an async function and checking if both the passwords that the user has entered match or not. If they match, we pass it along with the email to our “logInWithEmailAndPassword” function else we show an alert.

  5. Now you can use the “useAuthState” hook to manage the session. It returns some important information about the authentication state of our app.

    As the name suggests, the “user” variable will contain information about the active user, the “loading” variable will be a boolean value indicating the loading state and the “error” contains any error we may encounter during the authentication process.

  6. You can redirect users to a different page based on their authentication. 

    For example, you can redirect already logged-in users from the login page to a dashboard. To do so, we can use the “useEffect” that will run every time the “user” or the “loading” variables change.

  7. Similarly, any route that you want only the authenticated users to access can be protected as well, using the “useAuthState” & “useEffect” hooks.

    Over here if the user variable is undefined, we are navigating our users to a different page. Since we are passing an empty array as dependencies in our “useEffect” hook, it will run only once when the component is mounted.

  8. To log out users, you can use the “logout” function by importing and triggering it based on some user action

That’s it! This is how you can use Firebase in your React projects to protect routes and enable authentication for your users!

By following the steps above, you can turn your designs into production-ready React code with the ability to create users, sign them in as well as log them out.

With the Locofy.ai plugin, you will be able to generate pixel-perfect frontend code that can be broken down into components that can accept props and pages. 

By following the steps above, you can configure your Firebase project in the React app and protect the relevant pages behind an authentication layer by creating & signing in users.

Keep your loco mode on!
Stay updated on the latest Locofy announcements and product updates

© 2024, Locofy Pte Ltd. All Rights Reserved.