2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js (React) で何故か autoFocus が効かない

Last updated at Posted at 2023-01-01

問題

<input type="text" autoFocus={true} /> が何故か動作しない

解決

useRef やら useEffect やらを使う例が見つかった

pages/example.tsx

import type { AppProps } from 'next/app'
import React, { useEffect, useRef, useState } from 'react';

export default function AutoFocus({ Component, pageProps }: AppProps) {
  const inputElement = useRef(null);

  useEffect(() => {
    if (inputElement.current) {
      inputElement.current.focus();
    }
  }, []);

  return (
    <div>
        <input type="text" ref={inputElement} />
    </div>
  );
}

結果

image.png
Uploading image.png…

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?