Build a login form that appears and disappears (React.js)

Mav Tipi
2 min readDec 3, 2020

While doing a React project earlier this year, I built a login form that drops down from the header.

I’ll walk you through it. Since we’re working in React, we’ve got it organized into the following components:

The header imports and renders the login block, and the login block imports and renders the login form.

Header.js

There’s one more bit of functionality here. If there is a logged in user, we don’t display the login button/form at all, but rather a welcome message and a log-out button. For my purposes, that looked like this:

let welcome
if(this.props.currentUser){
welcome =
[<div>
Welcome!
<button onClick={this.handleLogout}>
Logout {this.props.currentUser.username}
</button>
</div>]
} else {
welcome =
<LoginBlock
handleUpdateCurrentUser={this.props.handleUpdateCurrentUser}
currentUser={this.props.currentUser}
/>
}

And then {welcome} in the render’s return. (In the above block, I’ve removed things like classNames and ids; you’ll probably want to play with such things to get your display how you want it.)

LoginBlock.js

LoginBlock has the signup/login buttons; on click, the “Log In” button calls this function:

Which toggles the login form’s display attribute between “block” and “none”. That’s the crux of this whole thing. Unlike what we did in the header with conditionally rendering the buttons and messages, LoginBlock’s render’s return always includes <LoginForm/>; it’s just this style toggling that determines whether it’s visible or not.

LoginForm.js

The only thing LoginForm specifically needs here is a className so that toggleLogin can find it. Above you can see that I used “smallform”.

CSS

You’ll need

.smallform {
display: none;
}

To set the default state. At this point, you’ve got an unstyled but functional version of the gif at the beginning of this post. Aside from aesthetic concerns, there is one major styling issue you’ll have to address in the CSS: The positioning of the login form on the page. Since that’s specific to how your page looks and what you want, I won’t address it.

--

--