stacky999
stacky999

Reputation: 31

Input field upon every input goes out of focus

Error occurs under two circumstances:

  1. If input has onChange

  2. If input is within component that is called on another page

For example:

On Page1.js we have:

return <div> <Page2 /> </div>

On Page2.js we have:

const [customState, customSetState] = useState({
   customText: ''
});

return <input value={customState.customText} onChange={setCustomStateText} />

function setCustomStateText(event) {
customSetState({
   ...customState,
   customText: event.target.value
 });
}

Error goes away when Page1 is not calling Page2 but just having normal input element, it also goes away once we remove onChange.

Any ideas?

Upvotes: 3

Views: 893

Answers (2)

stacky999
stacky999

Reputation: 31

Quick solution is with props.children, not the best solution, but it works. If anyone finds better solution let me know. If you set conditional rendering inside component use props.children to set render within another file.

Upvotes: 0

norbitrial
norbitrial

Reputation: 15176

I guess your input on each render has been recreated.

What about if you use useRef hook, as the documentation states:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Like the following:

const inputEl = useRef(null);
const [customState, customSetState] = useState({
   customText: ''
});

return <input ref={inputEl} value={customState.customText} onChange={setCustomStateText} />

The other issue what I see there which can cause further issues is not mutating the previous state. I suggest to use as the following:

function setCustomStateText(event) {
   customSetState(prevState => {
      return {
         ...prevState,
         customText: event.target.value
      }
   });
}

As the documentation states about setState():

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

I hope that helps!

Upvotes: 1

Related Questions