はじめに
複数ページにステップを分けた入力フォームを作成した際、必須項目を入力しなくても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 (
// (省略)
)
}