React Text Input Losing Focus After Each Keypress

David Ford
Level Up Coding
Published in
2 min readMar 25, 2022

--

This bug took me a while to figure out, so I thought I would share the cause and the fix.

I had a simple text input on a form.

And if you typed, say an ‘r’ into the text input, it would display the ‘r’ and then the focus would jump elsewhere. Not really sure where. But no longer in the text input. Thus the second character they typed would not show up.

If you wanted to type a whole word, like “foo”, you would have to type an ‘f’. Then click back into the text input. Then type ‘o’. Click back into the text input. Then type the final ‘o’.

Obviously that is messed up.

The problem was, I was defining a component inside of another component.

You can define functions inside of functions. And since my components are just functions, it makes since that you should be able to define one function component inside another function component.

But it won’t work.

You can define a component-like function inside of another component, like this:

const renderHeader = (x) => { return <div>{x}</div> }

renderHeader is simply a function that returns some JSX. It is not, strictly speaking, a react component. You can totally define that dude inside another function component and it works like a charm.

But make two tiny subtle changes, like this:

const RenderHeader = (props) => { return <div>{props.x}</div> }

Now, it’s a real component. And Boom!! Now you get crazy “losing focus” behavior.

To fix this, I simply moved the the RendorHeader function to be a top-level function and that fixed it.

--

--