React input автофокус с помощью ref

Представьте ситуацию, когда вам нужно поставить фокус в инпут. Для input’а, который есть на странице в момент загрузки — никаких проблем, в документации указано как использовать ref. Остается только вызвать метод .focus()

Но если элемента на странице нет, например, по клику на «Логин» появляется модальное окно, и в нем нужно установить фокус в input…

Ситуация так же решается с помощью ref 😉

class Input extends Component {
  focus() {
    this.el.focus();
  }
  
  render() {
    return (
      <input
        ref={el=> { this.el = el; }}
      />
    );
  }
}

Так как у стрелочных функций нет своего this, мы можем удобно присвоить в this.el (то есть Input.el в нашем случае) необходимый html-элемент. Именно html. У которого уже есть все методы, описанные в MDN. Отлично, теперь у нас есть метод, который установит фокус в инпут. Остается его откуда-то вызывать.

<code>
class SignInModal extends Component {
  componentDidMount() {
    this.InputComponent.focus();
  }
  
  render() {
    return (
      <div>
        <label>User name: </label>
        <Input
          ref={comp => { this.InputComponent = comp; }}
        />
      </div>
    )
  }
}
</code>

При этом, как говорится в оригинале: Note that when you use ref on a component, it’s a reference to the component (not the underlying element), so you have access to its methods.

Перевод: когда вы используете ref на компонент, то этот ref ссылается на компонент, а не на «низлежащий» html-код. Поэтому можно использовать методы компонента. Что мы и сделали, используя запись: this.InputComponent.focus()

comments powered by HyperComments
phwin99login
2026-04-14 11:47:06
Hey, just tried out phwin99login and the registration was surprisingly smooth. Site layout is pretty standard, nothing too fancy, but it gets the job done. Worth a look if you're exploring different options! Check it out: <a href='https://phwin99login.com' rel="nofollow ugc">phwin99login</a>
v9betvietnam
2026-04-14 11:47:23
Alright guys, so I checked out v9betvietnam. The Vietnamese site is cool, easy to navigate even for a newbie like me. Good promotions and some decent odds. Might be my new go-to spot! You can find it here: <a href='https://v9betvietnam.net' rel="nofollow ugc">v9betvietnam</a>
12betaffiliate
2026-04-14 11:47:40
Yo, looking for a good affiliate program? Saw some hype around 12betaffiliate and decided to take a peek. Seems legit, decent commission structure. Giving it a try! See what you think: <a href='https://12betaffiliate.net' rel="nofollow ugc">12betaffiliate</a>
При копировании материалов обратная ссылка на play-stop.ru желательна обязательна!