티스토리 뷰

useLocation()

사용자가 현재 머물러 있는 페이지에 대한 정보를 받아온다.

http://localhost:3000/home?keyword=react

 

location에서 pathname을 사용하면 쿼리를 제외한 /home을 가져오고 search를 하면 ?keyword=react 쿼리스트링을 가져온다.

useLocation을 선언하고 location.pathname이나 location.search로 접근할 수 있다.

import React from 'react';
import { useLocation } from 'react-router-dom';

const App = () => {
  const location = useLocation();
  console.log(location.pathname) // /home
  console.log(loaction.search) // ?keyword=react
  return (
    <h1>hi<h1/>
  );
}

export default App;

 

공식문서 예제

// https://v5.reactrouter.com/web/api/Hooks/uselocation
import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  useLocation
} from "react-router-dom";

function usePageViews() {
  let location = useLocation();
  React.useEffect(() => {
    ga.send(["pageview", location.pathname]);
  }, [location]);
}

function App() {
  usePageViews();
  return <Switch>...</Switch>;
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  node
);

+

offset

쿼리에서 key로 보여줄 시작점을 지정할 때 사용한다.

limit

쿼리에서 key로 보여줄 개수를 지정할 때 사용한다.

 

 

 

useParams()

path 파라미터를 얻어올 때 사용할 수 있다. useParams를 사용하려면 Router로 경로 설정을 해줘야한다. : 뒤에 변수이름이 파라미터가 되어 들어간다.

// App.js
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home'

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path='/home/:id' element={<Home />} />
      </Routes>
    </BrowserRouter>
  );
};

export default App;

 

useParams()를 사용해서 설정했던 변수명으로 접근하면 된다.

// Home.js
import React from 'react';
import { useParams } from 'react-router-dom'

const Home = () => {
  const params = useParams()
  return (
    <div>{params.id}</div>
  );
};

export default Home;

 

연습할 때는 useParams를 사용해서 id를 받아온 다음 그 아이디를 이용해 fetch로 해당 데이터를 불러왔다. 그리고 Card 컴포넌트에 데이터를 props로 넘겨줬다.

import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import Card from './Components/Card/Card';
import './MonsterDetail.scss';

function MonsterDetail() {
  const [monster, setMonster] = useState({});
  const navigater = useNavigate();
  const params = useParams(); // 파라미터 id 얻어오기

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((res) => res.json())
      .then((json) => {
        json.forEach((user) => {
          if (user.id === Number(params.id)) { // id를 사용해서 state값 변경
            setMonster(user);
          }
        });
      });
  }, [params]); // 파라미터가 변경 될 때마다 렌더

  return (
    <div className='urlParameters'>
      <div className='btnWrapper'>
        <button onClick={() => navigater('/monsters')}>
          Back to Monsters List
        </button>
      </div>
      <Card id={monster.id} name={monster.name} email={monster.email} /> {/* 받아온 데이터 props로 넘겨주기 */}
      <div className='btnWrapper'>
        <button
          onClick={() => navigater(`/monsters/detail/${Number(params.id) - 1}`)}
        >
          Previous
        </button>
        <button
          onClick={() => navigater(`/monsters/detail/${Number(params.id) + 1}`)}
        >
          Next
        </button>
      </div>
    </div>
  );
}

export default MonsterDetail;

 

공식문서 예제

// https://v5.reactrouter.com/web/api/Hooks/useparams
import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return <div>Now showing post {slug}</div>;
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
);

+

useHistory()

navigate를 사용하고 있다면 history에 대한 객체를 생성한다.

공식문서 예제

// https://v5.reactrouter.com/web/api/Hooks/usehistory
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함