🤖

【React】useLocation で 今いるページ・前いたページのpathを取得する

2024/03/13に公開

背景・目的

いくつかの手順を踏んで注文する形のECサイト構築中に、注文確認画面でのみ出力したいボタンがあったが、ボタンを置いているコンポーネントを流用したかったので試行。

また、注文の途中でログインを促す場合などは直前のページパスを取得する必要があったのでそれも試行。

備忘録。

サンプルコード

Sample.jsx
import React from "react";
import CustomButton from "../shared/Button/CustomButton";
import { useLocation } from "react-router-dom";
import './Sample.scss'
const Sample = ({ onPrevious, onNow }) => {
  const location = useLocation();
  const previousPagePath = location?.state?.from;
  const nowPagePath = location.pathname;
  return (
    <>
      <div className="l-sample">
        <div className="l-sample__wrapper">
          {previousPagePath === "previous-page" && (
            <CustomButton
              className={"l-sample__wrapper--previousPagebtn"}
              onClick={onPrevious}
            />
          )}
          {nowPagePath === "now-page" && (
            <CustomButton
              className={"l-sample__wrapper--nowPagebtn"}
              onClick={onNow}
            />
          )}
        </div>
      </div>
    </>
  );
};

export default Sample;

前いたページのパスを取得する

const location = useLocation();
const previousPagePath = location?.state?.from;
// ↑でどのパスからアクセスしてきたか取得する

今いるページのパスを取得する

const location = useLocation();
const nowPagePath = location.pathname;
// ↑で現在のパスを取得する

パスによって要素を出し分けする

//前のページが previous-page というパスだった場合
{previousRoute === "previous-page" && (
    //CustomButtom コンポーネントを出力する
    <CustomButton
      className={"l-sample__wrapper--previousPagebtn"}
      onClick={onPrevious}
    />
)}

Discussion