veeKINGPIN
veeKINGPIN

Reputation: 105

How to render input field as uncontrolled: ReactJS

I recently picked up React. Something about controlled and uncontrolled components confuses me.

For example, I have a custom input element like this TextInput.tsx

const TextInput: React.StatelessComponent<TTextInputProps> =
    ({ name, value, placeHolder, className, onChange, onBlur, onKeyPress }) => {
    return (
        <span>
            <input
                className={className}
                placeholder={placeHolder}
                **value={value != null ? value : ""}**
                name={name}
                onChange={onChange}
                onBlur={onBlur}
                disabled={disabled}
                onKeyPress={onKeyPress} />
            {
                validationFailed &&
                <div className="validation-error text">
                    {"some error text"}
                </div>
            }
        </span>
    );
};

And I use the component like this AnotherComponent.tsx

private accountNameOnChangeHandler = (event: any): void => {
    return event;
}

const returnItem = <TextInput
            name={"newAccountId"}
            **value={""}**
            onChange={this.accountNameOnChangeHandler}
            placeHolder="Account"
            className={"new-account-input"} />;

I am basically trying to render the TextInput custom component as uncontrolled. Because I do not want to deal with onChange of this component. I want the event to follow its natural course and change the value of the underlying HTML input element by itself.

What value do I have to send to keep the TextInput uncontrolled? Or should I simply render the HTML input directly in AnotherComponent.tsx?

Upvotes: 1

Views: 778

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104479

What value do I have to send to keep the TextInput uncontrolled?

To make the input element uncontrolled simply do not define the value property, means you are not controlling the value of the input element, whatever user will type it will reflect into DOM.

Like this:

<input
    className={className}
    placeholder={placeHolder}
    name={name}
    onChange={onChange}
    onBlur={onBlur}
    disabled={disabled}
    onKeyPress={onKeyPress} />

Or assign value={undefined} to input field.

If you want to set the initial value of input field, then use defaultValue property with input and pass its value from parent component.

Like this:

<input
    defaultValue = {props.defaultValue}
    ....
/>

Upvotes: 1

Related Questions