3
3

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 3 years have passed since last update.

【React】URL直打ちによるページスキップを防ぐ

Posted at

はじめに

複数ページにステップを分けた入力フォームを作成した際、必須項目を入力しなくてもURL直打ちでページスキップができてしまうということに気が付きました。
一瞬で登録完了!みたいなことをされたくなかったので、history.push()を少しいじってスキップを制御しました。

実装

「保存して次へ」ボタンNextButtonを押したときにhistory.push()でページ遷移を行いますが、この中にstate: { referrer: '/profile/one' }を付加します。

NextButton.tsx
export NextButton = () => {
  const history = useHistory()

  const handleClick = () => {
    history.push({
      pathname: '/profile/two',
      state: { referrer: '/profile/one' },
    })
  }

  return (
    <div style={{ marginBottom: 20, textAlign: 'center' }}>
      <Button
        type='submit'
        variant='primary'
        size='lg'
        style={{ width: 300 }}
        onClick={handleClick}
      >
        <span style={{ fontSize: 14, fontWeight: 'bold' }}>保存して次へ</span>
      </Button>
    </div>
  )
}

遷移先のページにuseEffectを追加し、history.location.stateに要素が入っていなければ/profile/oneにリダイレクトするようにします。
このようにすることで、URL直打ちでこのページに遷移しようとしても、'/profile/one'にリダイレクトされます。

ComponentTwo.tsx
export ComponentTwo = () => {
  useEffect(() => {
    if (!history.location.state) history.replace('/profile/one')
  }, [])

  return (
    // (省略)
  )
}
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?