I have to click the input after every character I type, because it loose focus. How can I do it, using the same function with name "InputArea". Because this problem doesn't arises when I don't use the function and write the code directly inside return.
CodePudding user response:
Define the InputArea component outside the parent component pass props to it. Because in your case, when the state changes, the component is re-rendered, and hence the InputArea component is redeclared.
Check out this article which addresses the same issue you have
function InputArea (props) {
return <input
type="text"
onChange={props.onChange}
value={props.value}
/>
}
function ParentComponent = () => {
const [name, setName] = useState('')
function onChange (e){
setName(e.target.value)
}
return (
<div>
<InputArea onChange={onChange} value={name} />
</div>
)
}
CodePudding user response:
each time you call the setName function you rerender the InputArea function. for fixing it you can wrap the function with a useCallBack hook or move the function out from the component.
const InputArea = useCallback(() => {
return (
<Input .../>
)
}, []);