Registration form input field in ReactJS keeps losing focus with every keystroke

Currently, I am in the process of creating a registration form for a website. I have implemented the handleChange function to alter the input text in the regData state. However, I am encountering an issue where every time I type something into an input field, the field loses focus after each keypress. For instance, if I intend to type "cool" in the input field, I need to click on the input field, press 'c', click again, press 'o', and repeat this process for each letter.

// Initialization of Errors and Navigate.
const [RegData, setRegData] = React.useState({
  firstname: '',
  lastname: '',
  username: '',
  email: '',
  password: '',
});

function handleChange(event) {
  const { name, value } = event.target;

  setRegData((prevRegData) => {
    return {
      ...prevRegData,
      [name]: value,
    };
  });
}

return (
  <Cont>
  <Logo to="/">Aurum.</Logo>
  <Container>
  <RegContainer>
  <Title>REGISTER</Title>

  <Form>
  <Input
  type="text"
  name="firstname"
  value={RegData.firstname}
  placeholder="First Name"
  onChange={handleChange}
  />
  <Input
  type="text"
  name="lastname"
  value={RegData.lastname}
  placeholder="Last Name"
  onChange={handleChange}
  />
  <Input
  type="text"
  name="username"
  value={RegData.username}
  placeholder="Username"
  onChange={handleChange}
  />
  <Input
  type="email"
  name="email"
  value={RegData.email}
  placeholder="Email"
  onChange={handleChange}
  />
  <Input
  type="password"
  name="password"
  value={RegData.password}
  placeholder="Password"
  onChange={handleChange}
  />
  <Input
  type="text"
  name="confPassword"
  placeholder="Confirm Password"
  onChange={handleChange}
  />

  <SignUpBtn>SIGN UP</SignUpBtn>
  </Form>

Here is the link to access the hosted version of the site along with the full source code

I have reviewed other forms that follow similar methods to mine, but I seem to be the only one facing this particular focus loss issue. Despite attempting to change functions and utilize callbacks, the problem persists with focus being lost after every keypress in the input fields.

Answer №1

After reviewing your code, I noticed that you are re-compiling styles with every render because your styled component is placed inside the function. It would be best to move it outside of the function for better performance.

Answer №2

relocate all your styled components to the top-level position

import React from 'react';
import styled from 'styled-components';
import { Link, useNavigate } from 'react-router-dom';
const Logo = styled(Link)`
  font-family: 'inter';      
  font-size: 35px;
        font-weight: bold;
        cursor: pointer;
        text-decoration: none;
        color: black;
        position: absolute;
        left: 2rem;
        top: 20px;

        &:hover{
          color: #1a1a1a;
        }
        
  `;

  const Cont = styled.div`
   position: relative;
  `;

  const Container = styled.div`
    font-family: 'inter';
    width: 100vw;
    height: 100vh;
    background: linear-gradient(
      rgba(255, 255, 255, 0.5),
      rgba(255, 255, 255, 0.5)
    ), url('https://images.unsplash.com/photo-1615405988866-94a0a4b0eac1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80');
    background-repeat: no-repeat;
    background-size: cover;
    display: flex;

    justify-content: center;
    align-items: center;
    background-position: center;
  `;

  const RegContainer = styled.div`
   background: white;
   border 2px solid rgba(1, 1, 1, 0.2);
   width: 600px;
   height: 600px;
   box-shadow: 2px 2px 50px;
   text-align: center;
 `;

  const Form = styled.form`
  margin-top: 0.5rem;
  margin-bottom: 1rem;

  @media (max-width: 1000px) {
   margin-top: 0    
  }

 `;

  const Input = styled.input`
  margin: 1rem;
  padding: 20px;

  @media (max-width: 1000px) {
    padding: 10px;  
    margin-bottom: 0 
  }
 `;

  const Title = styled.h1`
  margin-top: 3rem;
 `;

  const SignUpBtn = styled(Link)`
  display: block;
  margin: auto;
  margin-top: 0.5rem;
  padding: 10px 20px;
  width: 300px;
  height: 60px;
  border: none;
  cursor: pointer;
  background-color: rgba(54, 69, 79, 0.3);
  border-radius: 10px;
  font-weight: 400;
  font-size: 25px;
  text-decoration: none;
  color: black;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover{
    background-color: white;
    outline-style: solid;
    color: rgb(54, 69, 79);
  }

  @media (max-width: 1000px) {
   margin: 0
   padding: 10px;
   width: 150px;
   height: 30px;    
  }

 `;

  const Agreement = styled.span`
 margin-top: 1rem;
`;
export default function Register({ isLoggedIn }) {
  

  // Initializing all Errors and Navigate.
  const [RegData, setRegData] = React.useState({
    firstname: '',
    lastname: '',
    username: '',
    email: '',
    password: '',
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setRegData((prevRegData) => {
      return {
        ...prevRegData,
        [name]: value,
      };
    });
  }

  return (
    <Cont>
      <Logo to="/">Aurum.</Logo>
      <Container>
        <RegContainer>
          <Title>REGISTER</Title>

          <Form>
            <Input
              type="text"
              name="firstname"
              value={RegData.firstname}
              placeholder="First Name"
              onChange={handleChange}
            />
            <Input
              type="text"
              name="lastname"
              value={RegData.lastname}
              placeholder="Last Name"
              onChange={handleChange}
            />
            <Input
              type="text"
              name="username"
              value={RegData.username}
              placeholder="Username"
              onChange={handleChange}
            />
            <Input
              type="email"
              name="email"
              value={RegData.email}
              placeholder="Email"
              onChange={handleChange}
            />
            <Input
              type="password"
              name="password"
              value={RegData.password}
              placeholder="Password"
              onChange={handleChange}
            />
            <Input
              type="text"
              name="confPassword"
              placeholder="Confirm Password"
              onChange={handleChange}
            />

            <SignUpBtn>SIGN UP</SignUpBtn>
          </Form>

          <Agreement>
            By Signing Up, I agree and consent with the <b>Privacy Policy</b>{' '}
            and all that it contains.
          </Agreement>
        </RegContainer>
      </Container>
    </Cont>
  );
}

Here is the desired appearance

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

Achieving Center Alignment of Two Elements with Varying Widths in Relation to the Parent Container, all while maintaining Left Alignment and consistent indentation

I am currently working with Material UI, but maybe this is just a matter of understanding how to achieve it with Flexbox. Something similar to what is shown in the image below. I am struggling to make all three lines align in the same way on different scre ...

The SSE functionality is effective in a local environment, but encounters issues when deployed on Vercel's

Operating a proxy server, I send a request to OpenAI which responds with a Readable Stream object. The proxy server then redirects these events back to the client. While my code functions properly on a local deployment, it encounters issues when deployed ...

Utilize promise-style for Sequelize associations instead, please

I am in the process of merging information from 3 tables - Products, Suppliers, and Categories. My goal is to retrieve the row with SupplierID = 13. I recently came across a helpful explanation on How to implement many to many association in sequelize, whi ...

Opting for classes over IDs

Within the parent class, there are two divs. One is located using $(this).parent('div').next('.deal-rolldown').show(); while the other $(this).parent('div').next('.client-rolldown').show(); does not seem to function ...

Vue.js: Synchronization of props may not happen instantly

Struggling with using vue.js to synchronize a prop between parent and child components. The challenge is that sync relies on events, so every time I update the value, I have to wait for $nextTick before seeing the update. It's cumbersome to include $n ...

Issue with overlapping sticky dropdown and sticky navigation in Bootstrap 4

My issue revolves around getting the dropdown button menu to display in front of the vertical menu. When I click on the dropdown, the vertical (blue) menu takes precedence. This problem arose suddenly after applying the sticky-top class to both menus. Whil ...

Whenever the state of a React component is modified, it does not automatically trigger a re

Currently, I am utilizing the React Infinite Scroller library to display a list of posts. Interestingly, my load more results function seems to be triggered three times, resulting in the update occurring thrice (verified through console.log). For renderi ...

What are the disadvantages of using getBoundingClientRect() in ReactJS?

I recently incorporated the getBoundingClientRect() method into my project. However, a fellow React developer expressed concerns about its browser compatibility. In theory, shouldn't Webpack or Babel handle such compatibility issues? ...

Utilizing jQuery to apply a class to a targeted element when clicked

I'm currently working on animating a menu item where it expands to the left when hovered over, and contracts back when the mouse moves out. This part is functioning as expected. Additionally, I am trying to apply a specific color to the button by add ...

Positioning elements to the left and right of each other with CSS: tips and tricks

I'm currently working on aligning these elements one below the other, with one on the left and the other on the right: Here is my code snippet: Check out the fiddle here: https://jsfiddle.net/ak9hxfpt/2/ I want to position the test2 to the right sid ...

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...

Node.js API experiencing CORS issues even with the implementation of CORS middleware

UPDATE 4: Upon running the Node app with "yarn start" instead of pm2, I observed that a blank array is being returned rather than a 404 Not Found error. However, the CORS error still persists, albeit without the 404. UPDATE 3: It remains unclear to me wha ...

How can I implement a hover-over image change effect similar to the one seen in Gmail accounts?

I am attempting to implement a feature that allows users to change their image, similar to what can be done in a GMail account. When the user hovers over the image, an option to "change image" should appear. This may be a new concept for me because I am ...

Horizontal rule spans the full width of the content, appearing within an ordered list

Check out this example to see the issue with the horizontal rule not extending all the way across under the number. I've tried using list-style-position:inside;, but that interferes with positioning the number correctly due to the left image being flo ...

Discrepancy in listener state detected with ReactJS version 16.13.1 Hooks

I'm struggling to figure out why the magic doesn't work here. I've tried everything that comes to mind, but I can't seem to fix the problem. I'm attempting to use an array from the react state of my component in a websocket listen ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Steps for printing a web page with a custom stylesheet instead of the default print.css file

I have a print.css file that handles printing website pages, but I now want to create a basic-print.css file specifically for printing out basic information. How can I add a button to the page that triggers the print functionality using basic-print.css ins ...

Do not use npm to install underscore libraries

How can I resolve the error I encountered while attempting to install packages using npm? Here is my packages file: "dependencies": { "express": "~3.3.6", "socket.io": "0.9.16", "jade": "~0.35.0", "less-middleware": "~0.1.12", "redis ...

Changing the border color in a CSS pseudo-class does not take effect upon clicking

Is it possible to change the border color of an input field when clicked using CSS? I attempted to use the pseudo-class focus for this purpose, but encountered some issues. It seems to only work on select elements and not on elements like text inputs. . ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...