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 Router v6 画面遷移先に値を送る

Last updated at Posted at 2022-01-09

コンポーネント間での値の受け渡しについての記事です。

最初のページ(App.js)でLinkタグの属性stateで送りたい値を設定します。

App.js
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";
import NextPage from './NextPage';

const App = () => {
return (
    <Router>
      <div>
        <Link to="/next" state={{test: 'test'}}>
         <h5>NextPage</h5>
        </Link>
        <Routes>
          <Route path="/next" element={<NextPage/>}>
          </Route>
        </Routes>
      </div>
    </Router>
  )
}

export default App;

画面遷移先のページ(NextPage.js)でuseLocation()でlocationを取得し、更にlocationからstateを取得します。
画面遷移先のページで{"test": "test"}が表示されます。

NextPage.js
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";

const NextPage = () => {
  const location = useLocation();
  return (
    <div>
      {JSON.stringify(location.state)}
    </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?