DEV Community

Cover image for Create simple login form in React
Dirask-React
Dirask-React

Posted on • Originally published at dirask.com

Create simple login form in React

Hello there! πŸ‘‹πŸ˜Š

In this article, I would like to show you how to make a simple login form in React.

Before we start, I would highly recommend you to check out runnable example for the solution on our website:
Create simple login form in React

Final effect:image

Below I will try to explain to you how to create such a form in a few steps.

The whole structure of the example consists of the Field component, which will serve as a reusable code β™», and the Form, which puts it all together.

In our case, the style property was used for styling. 🎨

To get the values entered by the user in the inputs, I've used the useRef hook, with which we can easily obtain a handle to a DOM element and retrieve the current value.

Using these values, we build an object that we can then send to the server after handling onSubmit. πŸ“€

To prevent the page reloading onSubmit event, we explicitly called preventDefault() method.

πŸ“Note
By default ref property is reserved by React, so we should use the forwardRef function.

Practical example:

import React from 'react';
import ReactDOM from 'react-dom';

const appStyle = {
    height: '250px',
    display: 'flex'
};

const formStyle = {
    margin: 'auto',
    padding: '10px',
    border: '1px solid #c9c9c9',
    borderRadius: '5px',
    background: '#f5f5f5',
    width: '220px',
    display: 'block'
};

const labelStyle = {
    margin: '10px 0 5px 0',
    fontFamily: 'Arial, Helvetica, sans-serif',
    fontSize: '15px',
};

const inputStyle = {
    margin: '5px 0 10px 0',
    padding: '5px', 
    border: '1px solid #bfbfbf',
    borderRadius: '3px',
    boxSizing: 'border-box',
    width: '100%'
};

const submitStyle = {
    margin: '10px 0 0 0',
    padding: '7px 10px',
    border: '1px solid #efffff',
    borderRadius: '3px',
    background: '#3085d6',
    width: '100%', 
    fontSize: '15px',
    color: 'white',
    display: 'block'
};

const Field = React.forwardRef(({label, type}, ref) => {
    return (
      <div>
        <label style={labelStyle} >{label}</label>
        <input ref={ref} type={type} style={inputStyle} />
      </div>
    );
});

const Form = ({onSubmit}) => {
    const usernameRef = React.useRef();
    const passwordRef = React.useRef();
    const handleSubmit = e => {
        e.preventDefault();
        const data = {
            username: usernameRef.current.value,
            password: passwordRef.current.value
        };
        onSubmit(data);
    };
    return (
      <form style={formStyle} onSubmit={handleSubmit} >
        <Field ref={usernameRef} label="Username:" type="text" />
        <Field ref={passwordRef} label="Password:" type="password" />
        <div>
          <button style={submitStyle} type="submit">Submit</button>
        </div>
      </form>
    );
};

// Usage example:

const App = () => {
    const handleSubmit = data => {
        const json = JSON.stringify(data, null, 4);
        console.clear();
        console.log(json);
    };
    return (
      <div style={appStyle}>
        <Form onSubmit={handleSubmit} />
      </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

You can run this example here

So that's my version of the simple login form in React.

If you found this solution useful let me know in the comment section or just leave a reaction πŸ’—πŸ¦„πŸ’Ύ.
Thanks for reading and see you in the upcoming posts! 😊πŸ”₯πŸ”œ


Write to us! βœ‰

If you have any problem to solve or questions that no one can answer related to a React or JavaScript topic, or you're looking for a mentoring write to us on dirask.com -> Questions

You can also join our facebook group where we share coding tips and tricks with others! πŸ”₯

Oldest comments (8)

Collapse
 
hey_yogini profile image
Yogini Bende

Any reason for using ref over other methods for getting input values?

Collapse
 
diraskreact profile image
Dirask-React

Great question! 😊
The reason is to reduce our app re-renced cycles on state changes. Usually, states that describe inputs are updated when onChange event occurs that causes the whole component re-rendering on each small change (e.g. key press).

To get quicker answers you can ask in questions section on dirask.com/questions because I don't read the comments here every day 😊

Collapse
 
hey_yogini profile image
Yogini Bende

Absolutely. Component rerender becomes always a concern. I mostly use event.target.elements.inputname.value to get values from the form onSubmit. This is also good though.

Thanks for sharing.

Collapse
 
cklek profile image
Conrad Klek

Nice! I’m new to React. Can you style regular JavaScript html elements using the style property the way you did or is that a React specific feature?

Collapse
 
diraskreact profile image
Dirask-React

Hi!
Unfortunately, you can't assign object styles to the HTML elements, it's as you said specific React feature. πŸ™

Collapse
 
diraskreact profile image
Dirask-React

I've just prepared a solution for you. Let me know if this is what you wanted.
dirask.com/posts/pamEkp

Collapse
 
cklek profile image
Conrad Klek

This is great! I’ve been using a similar method for a while: stackoverflow.com/a/34490573/11218122

Collapse
 
saiganesh4299 profile image
saiganesh4299

Hello ! I am just starting to learn react . Can you please tell me what does the useref in the react do. We can also use state or usestate hook also right?