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

React hooksを使って、ページ遷移の制御をする

Posted at

react hooksを使って、ページ遷移(たぶ切り替え)の制御をした。
hashTagキーでurlの末尾に#~~と記述して、そのページに遷移できるようになる。

javascript
const setHashTag = (hashTag: string) => {
    navigate(`#${hashTag}`);
    setVal(hashTag);
  };

ここで、react hookの登場。useEffectを使う。
urlが変更されたときに起こる副作用をconst以下に記述。[location.hash, val]の配列が更新されるたびにEffect内の関数が実行される。

javascript
useEffect(() => {
    const currentHash = location.hash.replace('#', '');
    if (currentHash && currentHash !== val) {
      setVal(currentHash);
    }
  }, [location.hash, val]);
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?