0

I'm trying to add a onChange event to my input field component but when I the onChange evenet handler I can no longer type in my input component this is my input props interface

export interface InputFieldProps {
className?: string;
label?: string;
InputType?: 'email' | 'password' | 'search';
placeholder?: string;

onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

and this is my component call

<InputField
            label="Email"
            InputType="email"
            className="firstInput"
            placeholder="Email"
            onChange={(e) => {
                setEmail(e.target.value);
            }}
        />

and this is where I'm adding the prop onChange in my component (couldn't add code because it's too long)

enter image description here

1 Answer 1

1

You need to add the value prop to your InputField so that it actually displays that value. You are updating the email state, but not telling the InputField to display the email state.

<InputField
    label="Email"
    InputType="email"
    value={email}
    className="firstInput"
    placeholder="Email"
    onChange={(e) => {
      setEmail(e.target.value);
    }}
/>;

Should do the trick. Then all you need to do is make sure that in your you add value={value} and make sure the prop is unpacked the same place you unpack onChange.

I would give you a snippet but you have included a screenshot for this and not an actual code block.

UPDATE

Removing the logic from the styled component (removing onChange and value from the InputField function) seems to have resolved this issue for me in your fiddle.

I have to admit though I have a lot of experience with mui v4 I haven't read up on the new way of styling components in mui v5. However, I would guess that it is unwise to mix logic (state and state change) into the styled component. It seems like it is best to keep that separate.

See the changes I made here: https://codesandbox.io/s/xenodochial-northcutt-mkbbye?file=/src/InputField.tsx

Sign up to request clarification or add additional context in comments.

9 Comments

I've added value there but same problem, then I added value inside my component too this time it works but whenever I type something it goes out of focus. I have to click on the input field each time to type
add it to the inputfield and then make sure that you pass the props the same way you do with the onChange function. (Will update the answer)
If it still doesn't work after that last change I have just added, then please provide a working code fiddle
I did but still the same it goes out of focus after each time I type something. I will prepare a codesandbox
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.