dynamically focus on input (children component) using useRef doesn't work

780 views Asked by At

I have 'textRef' created in parent component and passed to children component using createRef(). I am trying to dynamically focus Input in children component on props change.

It does work when I test on localhost (chrome) but not on web view.

Any advice on this issue ? Thanks !!

parent component

const UserAddressForm = ({ query }) => {
  const textRef = useRef(null);

  const {
    state: { newAddress },
    saveMultiData,
  } = query;

  useEffect(() => {
    if (textRef && textRef.current) {
      textRef.current.focus();
    }
  }, [newAddress.zipcode]);

  const onAddressChange = (type, value) => {
    const addressObj = {
      ...newAddress,
    };

    ...

    saveMultiData({ newAddress: addressObj });
  };

  return (
    <InfoUl margin="21px 0px 0px;">
     ...
              <TextField
                ref={textRef}
                label=""
                name="addr2"
                placeholder="상세주소 입력"
                textField={newAddress}
                onInputChange={e => onAddressChange('addr2', e.target.value)}
              />
      
    </InfoUl>
  );
};

children component

import React from 'react';
import PropTypes from 'prop-types';
import { LabelBox, InputBox } from './styles';

const TextField = React.forwardRef(
  (
    {
      label = null,
      name,
      type,
      placeholder,
      textField,
      onInputChange,
      autoComplete,
      pattern,
      disabled,
      width,
      flex,
      marginRight,
      marginBottom,
    },
    ref,
  ) => (
    <LabelBox width={width} marginBottom={marginBottom}>
      {label !== null && <label htmlFor={label}>{label}</label>}
      <InputBox flex={flex} marginRight={marginRight}>
        <input
          ref={ref}
          type={type || 'text'}
          name={name}
          placeholder={placeholder}
          value={textField[name] || ''}
          onChange={onInputChange}
          autoComplete={autoComplete || 'on'}
          pattern={pattern || null}
          disabled={!!disabled}
        />
      </InputBox>
    </LabelBox>
  ),
);

version

React v16.9.0
1

There are 1 answers

0
Jiaah On BEST ANSWER

I resolved it by using input autoFocus attribute as well as ref attribute.

Since input appears dynamically on a button click, ref.focus won't work.

AutoFocus will get focus when the input appears.

Then Ref will get re-focus where the input is already placed on address re-search.