Timo
Timo

Reputation: 45

React Unfocuses Input Field When Typing

React refuses to keep focus on input field while typing.

I've tried to fix it, but was not successful. I don't understand this behaviour.

This is the component:

import React, { useState } from 'react'
import styled from 'styled-components'

const Auth = () => {
    const Form = styled.form``
    const InputGroup = styled.div``
    const Input = styled.input``
    const Button = styled.button``

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    return (
        <Form>
            <InputGroup>
                <Input
                    value={email}
                    onChange={event => {
                        setEmail(event.target.value)
                    }}
                    type="email"
                />
            </InputGroup>
            <InputGroup>
                <Input
                    value={password}
                    onChange={event => {
                        setPassword(event.target.value)
                    }}
                    type="password"
                />
            </InputGroup>
            <Button />
        </Form>
    )
}

export default Auth

codesandbox working example of the problem

Upvotes: 4

Views: 679

Answers (1)

Amit Chauhan
Amit Chauhan

Reputation: 6869

the problem is you are defining Input component inside your function which create new element each time so your new input lost focus. to fix problem define your component outside function.

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import styled from "styled-components";

const Form = styled.form``;
const InputGroup = styled.div``;
const Input = styled.input``;
const Button = styled.button``;

const Auth = () => {

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <Form>
      <InputGroup>
        <Input
          value={email}
          onChange={event => {
            setEmail(event.target.value);
          }}
          type="email"
        />
      </InputGroup>
      <InputGroup>
        <Input
          value={password}
          onChange={event => {
            setPassword(event.target.value);
          }}
          type="password"
        />
      </InputGroup>
      <Button>press me</Button>
    </Form>
  );
};

function App() {
  return (
    <div className="App">
      <Auth />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 6

Related Questions