2
2

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.

【React】useLocateの使い方

Posted at

useNavigateでページ遷移するときに遷移先に値を渡す

背景

useNavigateを使って遷移先のページに値を渡すときにpropsが使えないので困った

結論

useLocationを使用すればいい

値を渡す方法

渡し方

App.jsx
import { useNavigate } from 'react-router-dom';
function App(){
    const navigate = useNavigate();
    navigate('/',{state: {message: '成功', type: 'success'}});
}

受取り方

Rciept.jsx
import { useLocation } from 'react-router-dom'
function Reciept() {
    const location = useLocation();
    const message = location.state;
  return (
    <div>{message.message}</div>
  )
}

オブジェクトを渡す方法

渡し方

App.jsx
import { useNavigate } from 'react-router-dom';
function App(){
    const navigate = useNavigate();
    navigate('/',{state: user});
}

受取り方

Rciept.jsx
import { useLocation } from 'react-router-dom'
function Reciept() {
    const location = useLocation();
    const user = location.state;
  return (
    <div>{user.uid}</div>
  )
}
2
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?