0
votes

I'm having an issue with React with inputs automatically drawing focus.

I have one input field which I render upon mounting my component. I want to render a second input field below the first, only after I begin typing in that first input field.

The issue I'm running into is that the second input draws the cursor focus upon getting rendered, which I do not want.

One solution which isn't possible for me is hiding the second input with CSS, because I am trying to eventually make this input rendering setup generic beyond just a hardcoded two input fields (eg. upon typing in the second input field, render a third, upon typing in the third input field render a fourth, so on and so forth).

Is there any CSS property or something I can do in React to prevent inputs from automatically drawing focus? Thanks!

1

1 Answers

0
votes

You could implicitly focus on the first field instead, making sure the focus is set on the right field.

In react: create reference, and call focus on it:

import React, {useRef, useEffect} from "react"

function Form(){

    const myform = useRef();
    
    useEffect(function(){
      myform.current.children[0].focus();
    })
    
    return <form ref={myform}><input /></form>;

}