简体   繁体   中英

Space being added to the start of a form label using react-bootstrap?

I am trying to implement a form that is centered on the page, and has standard login inputs for email and password. The password label is implemented in the same way as the email input, and yet, the email label is being prepended with a ' ' space:

在此处输入图像描述

React component code:

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 LoginForm() {

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

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

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

    setValidated(true);

    let emailInputValue = event.target.querySelector('.email').value;
    let 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;
        }

    const 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);
                   const 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();
  };

  const 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>
    </>
  );
}

LoginForm.css

#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 have tried removing any margin and padding from the inputs, but it did not work.

Any help would be appreciated, thanks

I have Updated your code.

React component code:

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 LoginForm() {

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

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

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

setValidated(true);

let emailInputValue = event.target.querySelector('.email').value;
let 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;
    }

const 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);
               const 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();
};

const 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="12" 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="12" 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>
</>
);
}

LoginForm.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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM