리액트 버튼 클릭 페이지 이동 - liaegteu beoteun keullig peiji idong

새로운 페이지 만들기

src/pages/PurchasePage.js

import React from "react"; const PurchasePage = () => { return <div>PurchasePage</div>; }; export default PurchasePage;

onClick event에 함수 전달

버튼 onClick event에 위에서 선언한 arrow function navigateToPurchase 를 전달

src/pages/ListProductsSalePage.js 

<Button size="large" onClick={navigateToPurchase}> 구매하기 </Button>

src/pages/ListProductsSalePage.js 전체코드

import * as React from "react"; import ProgressBar from "../components/ProgressBar"; import { Box, Card, CardActions, CardContent, Divider, Button, Typography, } from "@mui/material"; import { useNavigate } from "react-router-dom"; const ListProductsSalePage = () => { const navigate = useNavigate(); const navigateToPurchase = () => { navigate("/purchase"); }; return ( <div> <br /> <Card sx={{ minWidth: 275 }}> <CardContent> <Typography variant="h5" component="div"> benevolent </Typography> <Typography variant="body2"> well meaning and kindly. <br /> {'"a benevolent smile"'} </Typography> <ProgressBar /> </CardContent> <Divider /> <CardActions> <Button size="large" onClick={navigateToPurchase}> 구매하기 </Button> </CardActions> </Card> </div> ); }; export default ListProductsSalePage;

import와 Route 추가

src/App.js

import PurchasePage from "./pages/PurchasePage"; <Routes> <Route path="/purchase" element={<PurchasePage />}></Route> </Routes>

실행 결과

구매하기 버튼 클릭 시 PurchasePage로 이동

참고 :

//reactrouter.com/en/main/hooks/use-navigate

//ko.reactjs.org/docs/handling-events.html

//bobbyhadz.com/blog/react- title-redirect

버튼을 눌렀을 때 화면이동을 해보겠습니다.

방법은 여러가지가 있습니다. window.location.href, replace 그리고 Link to를 이용하는 방법등이 있습니다.

먼저 window.location.href입니다.

window.location.href
href 실행화면
href 실행화면

다음은 window.location.replace입니다.

window.location.replace
replace 실행화면
replace 실행화면

 다음으로 Link to를 이용하는 방법입니다.

Link to
Link 실행화면
Link to 실행화면

 이렇게 여러가지 방법이 있습니다. 결과화면만 보았을 때는 replace와 href는 차이가 없어 보이실 수도 있지만 큰 차이가 있습니다. href는 뒤로가기 버튼을 누르면 뒤로 가지지만 replace는 뒤로가기 버튼을 누르면 뒤로가지지 않는 큰차이가 존재합니다. 그러니 뒤로가기를 방지하시고 싶으실 때에는 replace를 사용하시면 됩니다. (회원가입후 뒤로가기를 하면 큰일 나겠죠 ? ㅎㅎ) 오늘 하루도 열코하세요 !!

Toplist

최신 우편물

태그