Is there a way to include space at the beginning of a form label with react-bootstrap?

I am currently working on incorporating a form that is perfectly centered on the page, featuring standard login fields for both email and password inputs. Strangely enough, the label for the email input appears to be getting prefixed with an additional space character, even though the password label is set up in a similar manner:

https://i.sstatic.net/6bkt3.png

Here's the React component code I have:

import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
Col from 'react-bootstrap/Col';
Form from 'react-bootstrap/Form';
InputGroup from 'react-bootstrap/InputGroup';
Row from 'react-bootstrap/Row';
{useNavigate} from "react-router-dom";
{delay} from "../util/Util";
{Alert} from "reactstrap";
AuthService from "../services/AuthService";
"../css/LoginForm.css";
Logo400 from "../images/logo400.png";

export default function LoginForm() {

  {validated, setValidated} = useState(false);
  navigate = useNavigate();
  {alert, setAlert} = useState(false);
  {alertMessage, setAlertMessage} = useState('');
  {alertSeverity, setAlertSeverity} = useState('');

  handleSubmit = (event) => {
    event.preventDefault();

    const form = event.currentTarget;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    }

    setValidated(true);

    emailInputValue = event.target.querySelector('.email').value;
    passwordInputValue = event.target.querySelector('.password').value;

    if (validateInput(emailInputValue, passwordInputValue).includes("Failure: Email")) {
                    console.log("Validate input if failure email triggered")
                    setAlertMessage("Login failed, please enter a valid email, emails must be between 4 and 50 characters.");
                    setAlertSeverity("error");
                    setAlert(true);
                    return;
        }

        if (validateInput(emailInputValue, passwordInputValue).includes("Failure: Password")) {
                    console.log("Validate input if failure password triggered")
                    setAlertMessage("Login failed, please enter a valid password, passwords must be between 6 and 12 characters.");
                    setAlertSeverity("error");
                    setAlert(true);
                    return;
        }

    payload = {
                "email": emailInputValue,
                "password": passwordInputValue,
            };

    AuthService.loginUser(payload).then(response => response.json())
        .then(async data => {
            console.log(data);
                if (data.userId && data.accessToken) {
                   setAlertMessage("Login successful");
                   setAlertSeverity("success");
                   setAlert(true);
                   authenticatedUser = {
                    "userId": data.userId,
                    "accessToken": data.accessToken,
                    }

                    localStorage.clear();
                    localStorage.setItem("authenticatedUser", JSON.stringify(authenticatedUser));

                    await delay(1000);
                    navigate("/dashboard");
                }
            }
        );

    setAlertMessage("Login failed, probably because no user exists with these credentials.");
    setAlertSeverity("error");
    setAlert(true);

    localStorage.clear();
  };

  validateInput = (email, password) => {
          if (email.length > 50) {
              return "Failure: Email entered is too long."
          }
          if (email.length < 4) {
              return "Failure: Email is invalid."
          }
          if (password.length > 12) {
              return "Failure: Password is too long."
          }
          if (password.length < 6) {
              return "Failure: Password is too short."
          } else {
              return "Success."
          }
      }

  return (
  <>
    <div id="loginFormContainer">
       {alert ? <Alert severity={alertSeverity} role="alert">{alertMessage}</Alert> : <></> }
    </div>
    <div id="centerLogin">

    <div id="loginForm">
    <Form noValidate validated={validated} onSubmit={handleSubmit}>
      <Row className="mb-3">
      </Row>
      <Row className="mb-3">
        <Form.Group as={Col} md="4" controlId="validationCustom01">
          <Form.Label>Email</Form.Label>
          <Form.Control
            required
            type="email"
            placeholder="Email"
            className="emailLoginInput"
          />
        </Form.Group>
        </Row>
        <Row className="mb-3">
        <Form.Group as={Col} md="4" controlId="validationCustom02">
          <Form.Label>Password</Form.Label>
          <Form.Control
            required
            type="password"
            placeholder="Password"
            className="passwordLoginInput"
          />
        </Form.Group>
      </Row>
      <Button type="submit" id="loginSubmit">Submit</Button>
    </Form>
    </div>
    </div>
    </>
  );
}

In addition, here's the content of LoginForm.css file:

#centerLogin {
  display: flex;
  justify-content: center;
  text-align: center;
}

#loginLogo {
  width: 20vw;
  height: 40vh;
  position: relative;
  left: 0;
  padding-top: 40px;
}

#loginForm {
  width: 30vw;
  height: 20vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 80vh;
  background-color: white;
  margin-top: 10vh;
  border-radius: 10px;
  color: black;
}

.passwordLoginInput, .emailLoginInput, #loginSubmit {
  width: 20vw;
}

I've attempted removing any excess margin or padding from the input fields, but so far, it hasn't yielded the desired result.

If anyone has any suggestions or solutions, I would greatly appreciate your input. Thank you!

Answer №1

Hey there! I've made some improvements to your code.

Check out the updated React component:

import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import InputGroup from 'react-bootstrap/InputGroup';
import Row from 'react-bootstrap/Row';
import {useNavigate} from "react-router-dom";
import {delay} from "../util/Util";
import {Alert} from "reactstrap";
import AuthService from "../services/AuthService";
import "../css/LoginForm.css";
import Logo400 from "../images/logo400.png";

export default function EnhancedLoginForm() {

   const [validated, setValidated] = useState(false);
   const navigate = useNavigate();
   const [alert, setAlert] = useState(false);
   const [alertMessage, setAlertMessage] = useState('');
   const [alertSeverity, setAlertSeverity] = useState('');

// Rest of the code remains the same

const validateUserInput = (email, password) => {
      if (email.length > 50) {
          return "Failure: Email entered is too long."
      }
      // Add more validation rules here if needed
  }

return (
<>
<div id="loginFormContainer">
   {alert ? <Alert severity={alertSeverity} role="alert">{alertMessage}</Alert> : <></> }
</div>
<div id="centerLogin">

<div id="loginForm">
<Form noValidate validated={validated} onSubmit={handleSubmit}>
  <Row className="mb-3">
  </Row>
  // Updated form fields and validation code
</Form>
</div>

Also, don't forget to style your login form with the following CSS:

#centerLogin {
 display: flex;
 justify-content: center;
}

#loginLogo {
 width: 20vw;
 height: 40vh;
 position: relative;
 left: 0;
 padding-top: 40px;
}

#loginForm {
 width: 30vw;
 height: 20vh;
 display: flex;
 justify-content: center;
 align-items: center;
 min-height: 80vh;
 background-color: white;
 margin-top: 10vh;
 border-radius: 10px;
 color: black;
}

.passwordLoginInput, .emailLoginInput, #loginSubmit {
  width: 20vw;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Turn Off the overflow:auto; Feature in an Iframe on a Google Apps Script Web Application

While developing a web app using Google Apps Script, I have encountered an issue with the vertical scroll bar on the right side of the page. It seems to be present even when it's not necessary and does not function properly when scrolling. The web ap ...

Dealing with checkbox's checked and unchecked events using JavaScript

I am facing a challenge with a read-only textbox used for date input from a JavaScript date picker. Additionally, I have a gridview with checkboxes in the item template. My goal is to have the corresponding date filled in the textbox when a user clicks o ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Disable input with Safari colored background and transparency

Why does the CSS color #b3b3b3 turned white on a disabled input? What could be causing this and how can it be fixed? Take a look at this code snippet: https://jsfiddle.net/esty6t20/ CSS: .transp { background-color: transparent; } .bug-color { color: ...

The competition of JavaScript asynchronous operations

There exists an array of objects that is being expanded through parallel ajax requests. Once the last request is complete, the array needs to be processed. One possible solution can be seen below: function expandArray(objects, callback){ number_of_reque ...

Header spanning the entire width with varying ends

Hello everyone, I'm currently working on a website and struggling to create a header similar to the image shown above. I want the header to span the full width of the page. Can anyone provide guidance on achieving this using HTML5/CSS3 without relyin ...

Terminate the ongoing PHP script execution

Is there a way to terminate the current PHP script? For instance: page.php <?php require('./other-page.php'); ?> <h4>this text is always displayed</h4> other-page.php <?php if($_GET['v'] == 'yes&ap ...

Pausing briefly after selecting an element with Webdriver

I have been attempting to highlight an element on a webpage for a specific duration of time, approximately 5-6 seconds. However, I am facing difficulty in making the highlight persist for the desired duration as it currently flashes briefly. Despite using ...

"Incorporating PHP, CSS, and HTML to handle large volumes of data with dynamic columns and

I have a large dataset of around 10,000 entries that I need to display on my website. I am hoping to implement filters so that only a few thousand entries will be shown at a time. Languages: HTML, PHP, CSS After considering different options, I came up w ...

Tips for placing a button alongside an input field within a form-group and form-row class in Bootstrap 4

I am having trouble with aligning buttons inline with input fields using Bootstrap classes. Whenever I try to place a button next to an input field, it either drops below the input or doesn't stay aligned properly. Specifically, I would like to posi ...

My goal is to utilize vanilla JavaScript to highlight the anchor that was clicked and then remove the highlighting from any previously highlighted anchor

Hello everyone, this is my first time posting here and I'm still trying to figure things out, so I appreciate your patience. Currently, I am experimenting with vanilla JS to create a functionality where clicked anchors are highlighted while removing ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

Encountering the 'dispatcher is null' error when implementing react-dom-router and BrowserRouter, Routers, Route for a navigation bar component in a React application

I am currently working on building a header with multiple nested components, one of which is the NavBar component. I am now focusing on implementing functionality to make the NavBar items functional using BrowserRouter, Routes, and Route. Below is the code ...

Steps to resolve the white-dot border problem plaguing your dropdown menu

On my website, I've designed a drop-down menu with borders set to gray on the top, left, and right sides, while the bottom border is white. This creates a smooth, continuous border that looks great in FF3 and Chrome. However, after upgrading to FF4 o ...

Assigning a characteristic to every element within a collection

I have a project in progress where users need to click on a specific location, which will then take them to that location using Google Maps. The locations are stored as an array of objects, and here is how the location files are structured. $scope.SiteLoc ...

The checkValidity function fails to identify incorrect "tel" input

In my form, I am using the checkValidity function to validate inputs. However, I have encountered an issue where the validation only works when an input with the required attribute is missing a value. It doesn't work if there is a value type mismatch, ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

Utilizing vanilla JavaScript to sort selected checkboxes into a JSON object

I've been trying to implement a difficulty filter based on checked checkboxes, but despite my ongoing search for solutions, I haven't been able to find any promising results or clear directions. Exploration I came across a code snippet that see ...

Property missing in Typescript type definition

In my Typescript Next project, I am using this component: import PageTitle from './pagetitle' import style from './contact.styl' export default function Contact() { return ( <section> <a name="contact"> ...

Dynamic camera movement in JavaScript-driven HTML5 canvas game

I am currently working on a 2d HTML canvas game that functions well. However, I would like to implement a scrolling camera so that the player cannot see the entire map at once. Unfortunately, I have no idea how to achieve this and my attempts to research o ...