LoginSignup
0
0

【React】Input属性でタブを押したときの初期フォーカス位置を調整する

Last updated at Posted at 2023-12-26

結果

SelectionAPIを使った

ezgif-4-d89ef571cc.gif

めっちゃいろんなことを検索したけどreact関係なくSelectionAPIでやるのが便利だと思った次第。
普通にuseRefのドキュメントとか見てたけどこれでいいのでは。

window.getSelection().collapseToStart()

コードとコードサンドボックス

import { useRef, useEffect } from "react";
import "./styles.css";

export default function App() {
  const ref = useRef(null);

  useEffect(() => ref?.current?.focus(), [ref?.current]);

  return (
    <div className="App">
      <h1>タブ押したときのフォーカス位置</h1>
      <div>
        <input ref={ref} defaultValue="初期選択" />
      </div>
      <div>
        <input defaultValue="何もなしは全選択" />
      </div>
      <div>
        <input
          onFocus={() => window?.getSelection().collapseToStart()}
          defaultValue="先頭カーソル"
        />
      </div>
      <div>
        <input
          onFocus={() => window?.getSelection().collapseToEnd()}
          defaultValue="末端カーソル"
        />
      </div>
      <div>
        <input
          onFocus={() => window?.getSelection().deleteFromDocument()}
          defaultValue="選択を削除"
        />
      </div>
    </div>
  );
}

0
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
0
0