Next.js Discord

Discord Forum

My input component deselects when typing

Answered
Jersey Wooly posted this in #help-forum
Open in Discord
Avatar
Jersey WoolyOP
I've created an component that returns an input
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)
View full answer

20 Replies

Avatar
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
Avatar
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
Avatar
Risky
really random idea, can you try adding the key prop and making it a string of anything and see if it stays then
Avatar
Jersey WoolyOP
Didn't work 😔
Avatar
Risky
😭
can you share more code on where this is defined and used maybe
Avatar
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?
Avatar
Risky
im just looking at it right now and i can't seem to be able to abuse 😭
Avatar
Jersey WoolyOP
In the handleInputChange?
😢
don't understand
Avatar
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
Avatar
Jersey WoolyOP
Why does it even recreate the input component instead of updating it? Like regular html would do
Avatar
Jersey WoolyOP
The solution was to declare the SimpleField component outside the main CreateClientForm because it re-renders the main component (i guess)
Answer
Avatar
Risky
oh that makes sense, but ahhhh