View
React 기초
React
React는 자바스크립트 라이브러리로, “컴포넌트”라고 불리는 단위를 이용하여 복잡한 UI를 구성하도록 돕습니다.
React 앱 만들기
1. Node.js 설치
- 공식 홈페이지에서 LTS 버전 설치
- 설치 후 cmd 창에서 node -v npm -v 명령어 실행해서 현재 버전 확인하기 (잘 설치되었는지 확인)
2. React 설치
- npm i react
3. React App 생성
- npx create-react-app my-app
- my-app은 생성할 App 이름입니다
- typescript 버전: npx create-react-app my-app --template typescript
4. 실행
- cd my-app
- npm run start 혹은 npm start
state와 props
- state
- 컴포넌트 내부에서 바뀔 수 있는 값.
- props
- 컴포넌트 속성을 설정할 때 사용하는 요소. 부모 컴포넌트에서 자식 컴포넌트한테 전달하는 속성이라고 생각하면 됨.
Hooks
리액트 컴포넌트는 클래스형 컴포넌트와 함수형 컴포넌트로 나뉘어지는데 이 Hooks들은 함수형 컴포넌트에서는 할 수 없었던 다양한 작업을 할 수 있게 해 줍니다.
useState
- 함수형 컴포넌트에서도 state를 관리하게 해 줍니다.
const [num, setNum] = useState(0);
num이 state가 되고, setNum이라는 setter 함수를 이용해 0으로 설정되었던 default 값을 변경할 수 있다.
useEffect
- 특정한 시기에만 코드들을 실행하고 싶을 때 사용합니다.
useEffect(() => {
...
return (...);
}, []);
... 에 해당하는 코드 블럭은 이 컴포넌트가 처음 렌더링 될 때만 실행됩니다.
[ ]에 특정 변수를 넣으면 그 변수가 바뀔 때마다 실행할 수 있습니다.
return으로 컴포넌트의 끝(소멸되기 전?)에 코드를 실행시킬 수 있습니다.
useMatch
- 현재 url 상태가 일치한다면 true, 다르다면 false를 반환
- react-router-dom
const match = useMatch("/:coinId/price");
console.log(match)
react-router-dom
import React from "react";
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Auth from "routes/Auth";
import Home from "routes/Home";
import Profile from "routes/Profile";
import Create from "routes/Create";
import Navigation from "components/Navigation";
const AppRouter = ({ isLoggedIn }) => {
return (
<Router>
{isLoggedIn && <Navigation />}
<Routes>
{isLoggedIn ? (
<>
<Route exact path="/" element={<Home />}></Route>
<Route exact path="/profile" element={<Profile />}></Route>
<Route exact path="/create" element={<Create />}></Route>
</>
) : (
<>
<Route exact path="/" element={<Auth />}></Route>
</>
)}
</Routes>
</Router>
);
};
export default AppRouter;
Routes
- 경로가 적합한 처음 컴포넌트를 찾아 줍니다.
Route
- 컴포넌트의 일종으로, 다른 컴포넌트로 이동할 수 있게 한다.
<>
<Route exact path="/" element={<Home />}></Route>
<Route exact path="/profile" element={<Profile />}></Route>
<Route exact path="/create" element={<Create />}></Route>
</>
- url이 “/”일 경우 Home 컴포넌트 보여 줌
- url이 “/profile”일 경우 Profile 컴포넌트 보여 줌
- url이 “/create”일 경우 Create 컴포넌트 보여 줌
Link
- html <a> 기능과 유사. 다른 점은 클릭하면 새로고침 되지 않음
- /home으로 이동하고, Router에서 /home에 해당하는 컴포넌트를 찾아 보여 줄 것임.
<Link to="/home">홈</Link>
- 객체를 담아서 전달할 수도 있다
<Link to={`/detail/${id}`} state={{name, desc, num: number}}>
상세 페이지
</Link>
중첩 라우팅 (nested routing)
- 라우트 안에서 또 라우트 컴포넌트를 연결해야 하는 경우
- 부모 route의 path 마지막에 /*를 적어 명시적으로 이 route의 내부에서 nested route가 render 될 수 있음을 표시하고 자식 route를 부모 route의 element 내부에 작성한다.
- <Outlet> 사용
- 여기서도 /* 사용은 필수
/// Router.js <Routes> <Route path="web/*" element={<Web />}> <Route path=":id" element={<WebPost />} /> </Route> </Routes>
// Web.js // props 못 넘김..;; <Outlet />
- Router.js 에서 중첩 라우팅을 사용한 후, 중첩 라우터에서 <Outlet> 컴포넌트 사용한다.
1. 설치
- npm i react-router-dom
jsconfig.js
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"],
"exclude": ["node_modules"]
}
- jsconfig.js 파일을 루트에 추가해 모듈을 import 할 때 상대경로가 아닌 from “components/Form” 같은 식으로 데리고 올 수 있습니다
'Front-End > React' 카테고리의 다른 글
[Trouble-Shooting] persist로 저장되어 있는 redux state에 field가 추가되는 경우 (0) | 2022.09.22 |
---|---|
[Trouble-Shooting] Redux Thunk (0) | 2022.03.06 |
Redux 기초 - 노션 백업 (0) | 2022.03.06 |