React/Rails Authentication: Client Initialization

This is the second entry in setting up a React and Rails authentication app. The first entry on API Configuration can be found here.

Let’s get right into it by initializing our React app

npx create-react-app auth-app

Once that’s all finished, you should then run npm install and npm start.

If done correctly, you should see the spinning React logo in your browser. The first thing we want to do is create a component in out src folder. Let’s call it Home.js.

If you’re using Visual Studio Code, I highly recommend downloading an extension called React Snippets. With this extension, you can generate the boilerplate code for any component that maintains state by typing rcc and then pressing the Tab key when the menu pops up. Regardless, our newly formed component should look like this:

import React, { Component } from 'react';export default class Home extends Component {   render() {     return (      <div>       <form>
<input
type="text"
name="username"
placeholder="Enter Username..." />
<input
type="password"
name="password"
placeholder="Enter password..." />
<input type="submit" value="Log In" /> </form> </div> ) }}

I added a very simple form so that when we render the Home component, we’ll have some elements added to the DOM. Next, let’s go import our new component in App.js.

In App.js, we want to drop our new component nested inside of <div className="App">. When you start to type Home, VS Code should give you a small popup menu to autofill in the rest of the component. In selecting this, it will generate the import statement for you. Otherwise, your App component should now look like this:

import React from "react";
import './App.css';
import Home from './Home.js';
function App() {
return(
<div className="App">
<Home />
</div>
)
}

Now, when you open your browser, you should see a barebones form with two input fields and a submit button that says “Log In”. Now that the form is rendering, let’s move back to the Home component.

There are two key functions that we need right away, and those are handleSubmit() and handleOnChange(). Additionally, we also immediately need to set up our initial state. The state of this component is going to track the user input and send that data to our API, so we define it at the top of the component:

state = {
username: '',
password: ''
}

Now we have an initial state object that has two keys that point to empty strings. We can then build out our handleOnChange() function to track our state changes. It’s important for me to mention that if you haven’t already, you should install the React DevTools extension for Google Chrome. This adds two tabs to your browser console that will allow you to see the state changes in your components. Let’s build out that handleOnChange():

handleOnChange = event => {
this.setState({
[event.target.name]: event.target.value
})
}

This function is an arrow function that takes in the event as an argument. Using React’s synthetic events, this function’s purpose is to save our state changes by reading the name of the input field that the user is typing into and sets it equal to whatever the user actually types. For example, typing ‘ctd’ into the username field will change our state like so:

state = {
username: 'ctd',
password: ''
}

The password key isn’t updated until we actually type something into the password field. In fact, neither one of them will truly be updated until we make changes to the form.

In the form itself, we need to add some props to our <input> tags. The most important one to add is onChange, a prop that triggers whenever the element it is attached to undergoes any kind of change. This prop then takes a callback function, so we want to add onChange={this.handleOnChange} to our <input> fields. Additionally, we want to add a value prop that is equal to the current state of that particular <input>. Here’s an example:

<input
type="text"
name="username"
placeholder="Enter username..."
onChange={this.handleOnChange}
value={this.state.username} />
<input
type="password"
name="password"
placeholder="Enter password..."
onChange={this.handleOnChange}
value={this.state.password} />

The next key function we need is handleSubmit(). This function will be passed as a callback function to our form through a prop called onSubmit, very similar to how we did the onChange prop. First, let’s build the actual function:

handleSubmit = event => {
event.preventDefault();
console.log(this.state)
this.setState({
username: '',
password: ''
})
}

This function does a couple of things for us. First off, preventDefault() prevents our form from causing a page refresh when submitted. The next line is simple, we just want to log our current state to the console. Finally, we are resetting the state to its initial values. Additionally, this part ties into why we added value props to the <input> fields earlier. Without that prop, submitting the form would keep the forms populated even though we reset the state. It more closely emulates regular form behavior.

Our Home component should be pretty full now. Here’s a preview of what the (almost) final product should look like:

export default Home extends Component {
state = {
username: '',
password: ''
}
handleOnChange = event => {
this.setState({
[event.target.name]: event.target.value
)}
}
handleSubmit = event => {
event.preventDefault();
console.log(this.state);
this.setState({
username: '',
password: ''
})
}
render() {
return(
<form onSubmit={this.handleSubmit} >
<input
type="text"
name="username"
placeholder="Enter username..."
onChange={this.handleOnChange}
value={this.state.username} />
<input
type="text"
name="username"
placeholder="Enter username..."
onChange={this.handleOnChange}
value={this.state.username} />
<input type="submit" value="Log In" />
</form>
)
}

And there you have it! This component captures user input and will log it into the browser console when submitted. So far, we’ve set up an API and a client. In the next guide, we will connect the two ends to set up log in functionality, log out functionality, and maintaining logged in state client-side.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store