이번에는 useNavigate를 이용하여 사이트 이동버튼을 만들어볼건데요 !
일단 useNavigate를 react-router-dom으로부터 import해줍니다.
import { useNavigate } from "react-router-dom";
useNavigate()의 변수 navigate를 만들어줍니다.
6~10 : MyButton의 props로 type, text, onClick을 전달해줍니다.
이 때 props를 전달하는 것이기에 {중괄호}로 감싸야 합니다.
9 : onClick의 함수로 navigate()를 전달하는 것입니다. 현재 주소에서 /new를 붙힌 주소로 이동시킬 것이기 때문에 navigate("/new")라 작성해줍니다.
const DiaryList = ({ diaryList }) => {
const navigate = useNavigate();
return (
<div>
<MyButton
type={"positive"}
text={"새 일기 쓰기"}
onClick={() => {
navigate("/new");
}}
/>
</div>
);
};
MyButton Component입니다.
props로 text,type,onClick을 전달받았습니다.
전달받은 props를 이용해 <button>요소를 만들어 return해줍니다.
이 때, type이 positive, negative가 아닌 값을 전달받았다면 기본 값으로 default를 설정해 줍니다.
import React from "react";
const MyButton = ({ text, type, onClick }) => {
// type이 positive,negative가 아니라면 default로 설정
const btnType = ["positive", "negative"].includes(type) ? type : "default";
return (
// className을 띄어쓰기 간격으로 합쳐줌
<button
className={["MyButton", `MyButton_${btnType}`].join(" ")}
onClick={onClick}
>
{text}
</button>
);
};
MyButton.defaultProps = {
type: "default",
};
export default MyButton;
'WebProgramming > React' 카테고리의 다른 글
[React] useContext를 이용해 전역 props전달하기 (0) | 2022.07.09 |
---|---|
[React] useParams를 이용해 파라미터 가져오기 (0) | 2022.07.09 |
[React] 자식 Component에서 부모 Componet로 값 변경하여 전달하기 (0) | 2022.07.09 |
[React] 저장된 이미지들을 한번에 나열(보간법 사용) (0) | 2022.07.09 |
[React] 최신 순 / 오래된 순 정렬 (0) | 2022.07.08 |
[React] useState로 input 상태 관리하기 (0) | 2022.07.07 |
[React] MyButton을 만들어 재활용하기 (0) | 2022.07.07 |
[React] 라우팅(react-router-dom)(useParams, Query) (0) | 2022.07.07 |