My input component deselects when typing
Answered
Jersey Wooly posted this in #help-forum
Jersey WoolyOP
I've created an component that returns an input
But everytime I type something in, it loses focus (Deselects). The input is correctly registered and I can continue writing clicking between each letter.
This is my handleInputChange function:
Any explanation would be very appreciated 😄
const SimpleField = ({ placeholder, id, type }: { placeholder: string; id: string; type: string }) => {
return(
<input type={type} placeholder={placeholder} id={id} onChange={handleInputChange} value={formData[id]}/>
)
}
But everytime I type something in, it loses focus (Deselects). The input is correctly registered and I can continue writing clicking between each letter.
This is my handleInputChange function:
const handleInputChange = (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
e.persist();
const { id, value } = e.target;
setFormData({
...formData,
[id]: value,
});
};
Any explanation would be very appreciated 😄
Answered by Jersey Wooly
The solution was to declare the
SimpleField
component outside the main CreateClientForm
because it re-renders the main component (i guess)20 Replies
risky
remove the value part in input because i think that recreates the input thing every change (thus deselect), you can use defaultValue if you want to preload some state tho
Jersey WoolyOP
I've already tried using defaultValue and removing value at all. Also when working with normal inputs (not react components) it works just fine
I also think that it recreates the input every time, but I'm struggling to find a solution
risky
really random idea, can you try adding the
key
prop and making it a string of anything and see if it stays thenJersey WoolyOP
Didn't work 😔
risky
ðŸ˜
can you share more code on where this is defined and used maybe
you might also be able to scam [
.focus()
](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus)Jersey WoolyOP
This is the basic structure
// app/home/page.tsx
export default function Home(){
// returns the page... and
<CreateClientForm></CreateClientForm>
}
// app/components/newClient.tsx
const CreateClientForm = () => {
handleInputChange(){...}
SimpleField(props){...}
// More code
return ({
<div>
<form>
<SimpleField></SimpleField>
//...
})
}
Where should I use it?
risky
im just looking at it right now and i can't seem to be able to abuse ðŸ˜
Jersey WoolyOP
In the handleInputChange?
😢
don't understand
risky
yeah that is what i thought
but it seems like as it recreates everything it can't seem to be easy
i was trying to think using the id and documentgetelementbyid but that didn't seem to work
Jersey WoolyOP
Why does it even recreate the input component instead of updating it? Like regular html would do
Jersey WoolyOP
The solution was to declare the
SimpleField
component outside the main CreateClientForm
because it re-renders the main component (i guess)Answer
risky
oh that makes sense, but ahhhh