🗺️

【React】ページのpathを取るhooksを作った

2023/01/20に公開約500字
src/libs/useGetPathname.ts
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export function useGetPathname() {
  const [getPathname, setGetPathname] = useState<string>('');
  const router = useRouter();
  useEffect(() => {
    setGetPathname(router.pathname);
  }, []);
  
  return getPathname;
}
pages/index.tsx
import { useGetPathname } from '../src/libs/useGetPathname';

const Home: NextPage = () => {
  const getPathname = useGetPathname();
  console.log(getPathname);
  // 省略
};

export default Home;

Discussion

ログインするとコメントできます