Just-in-Time Learning initiative

Version 1.1

This tutorial shows you how to create the building blocks of a login screen such as input forms. We'll also set a variable to check whether the user has logged in, and only show sensitive information once they have.

We'll assume you know how to make custom components and hooks in React Native. We'll also assume you already have a multi-screen app whose initial screen is WelcomeScreen.js.

Note: this draft presents only a rudimentary synopsis of this tutorial. Please watch the video for details.

Create login components

Let's say you have a simple WelcomeScreen.js with a simple button users can click to proceed, but you want them to log in first to ensure user privacy or accountability. We're going to create a <LoginForm> component to stand in its place until the user has logged in.

We'll build our login form from a series of nested components, including input fields and a submit button. We'll make these as generic as possible so we can re-use them for other screens or apps.

1. SubmitButton.js

React Native SubmitButton ScreenshotThis will be just a re-usable button that looks a little better than the one that comes by default with React Native.

2. Input.js

React Native Input ScreenshotNext we'll make a simple <Input> component with a label and input field.

3. LoginForm.js

React Native LoginForm ScreenshotNow we'll combine these to make a form to enter the user's credentials.

Add the login form to your welcome screen

React Native WelcomeScreen Screenshot BReact Native WelcomeScreen ScreenshotLet's make the login form the first thing users see when opening the app.

Show a different welcome screen if the user is logged in

We'll do this by writing an if statement in our JavaScript. It will test for a variable we'll call isLoggedIn that we'll change from false to true when the user logs in.

But we still need to determine the value of isLoggedIn in WelcomeScreen.js even though it's set in the child component LoginForm.js. How do we pass information from a child component to its parent?

Pass the "logged in" state to the parent component

As we know from previous tutorials, you can pass data down to child component by writing custom properties, or "props," as attributes into the tag in the parent.

However, you can also pass data upwards, from the child to the parent, if one of those attributes is a function called in the child but defined in the parent. This is called "lifting the state up."

Fortunately, we can use the onSubmit listener we already built into <LoginForm> to trigger the change in LoginForm.js and have it percolate back to WelcomeScreen.js.