Tammy
Tammy

Reputation: 1132

ReactJs: How to back focus to input field after resetting the form

How could I set the focus back to the input field after resetting the field?

Thanks

//code

<div
            className={cn("input-border-wrapper", { "is-disabled": disabled })}
          >
            <input
              placeholder={label}
              required={optional === null ? !!required`${name}` : !optional}
              readOnly={readonly}
              aria-describedby={describedByIds}
              autoComplete={autocomplete`${name}`}
              inputMode={inputmode`${name}`}
              {...validations`${name}`}
              {...this.props.input}
              {...{ disabled, id }}
              type={type || inputtype`${name}` || "text"}
              ref={refCallback}
            />
          </div>
          {(optional === null ? !required`${name}` : optional) &&
            !hasValue && (
              <span className="input-wrapper--optional">{optionalLabel}</span>
            )}
          <InputIcon
            ariaLabel={buttonAriaLabel}
            hasClearIcon={
              shouldShowClearIcon && hasValue && (isActive || hasError)
            }
            hasCalendarIcon={
              button === "lh-datepicker" || icon === "lh-datepicker"
            }
            name={button || icon}
            onClick={onButtonClick}
            onMouseDown={() => clearInputValue(form, name, "")
            }
            {...{ disabled, hasIcon, hasButton }}
          />

Upvotes: 1

Views: 1512

Answers (2)

Vijay sadhu
Vijay sadhu

Reputation: 500

Use autoFocus with input element:

  <input autoFocus />

call it on reset click

  formReset(){
    this.focus();
  }

Upvotes: 0

Vencovsky
Vencovsky

Reputation: 31565

For Class Components

You should pass to the input a ref

<input ref={inputRef => this.inputRef = inputRef } {...} />

And get the set .focus on the input ref.

resetForm = () => {
    this.inputRef.focus()
}

For Functional Components

You should use useRef hook.

const inputRef = useRef(null);

Pass inputRef to the input

<input ref={inputRef} {...} />

And get the set .focus on the input ref using current(wich points to the mounted input element).

const resetForm = () => {   
    inputRef.current.focus()
}

Upvotes: 3

Related Questions