npm i styled-components
styled.{element}``;
&
: 가상 선택자로 자기 자신을 뜻함import styled, {keyframes} from 'styled-components';
const Wrapper = styled.div`
display:flex;
height:100vh;
width:100vw;
justify-content:center;
align-items:center;
background-color:${props => props.theme.backgroundColor};
`;
const Btn = styled.button`
color:white;
background-color: tomato;
border:0;
border-radius:15px;
`;
const rotateAnimation = keyframes` // Animation
0% {
transform:rotate(0deg);
border-radius:0px;
}
50% {
border-radius:40px;
}
100% {
transform:rotate(360deg);
border-radius:0px;
}
`;
`;
const Box = styled.div`
background-color:${props => props.bgColor};
width:100px;
height:100px;
display:flex;
justify-content:center;
align-items:center;
animation:${rotateAnimation} 1s linear infinite;
${Emoji}:hover {
font-size:98px;
}
`;
/* Box의 스타일을 상속받고 다른 스타일도 추가 적용 */
const Circle = styled(Box)`
border-radius:50%;
`;
/* 여러번 사용하는 경우 styled-component를 사용하여 속성을 한번만 설정해줌으로써 중복을 제거할 수 있음 */
const Input = styled.input.attrs({required:true})`
background-color:${props => props.theme.textColor};
`;
const Text = styled.h1`
color:${props => props.theme.textColor};
`;
function App() {
return (
<Wrapper as="header"> // as를 사용함으로써 div가 아닌 header로 동작하게 함
<Btn>Log in</Btn>
<Btn as="a" href="/">Log in</Btn>
<Box bgColor="tomato">
<Emoji>😊</Emoji>
</Box>
<Circle bgColor="orange"/>
<Input/> // styled-component를 사용해 required 설정됨
<Input/> // styled-component를 사용해 required 설정됨
<Emoji>🌠</Emoji>
<Text>Hello</Text>
</Wrapper>
);
}
npx create-react-app 프로젝트명 --template typescript
yarn create react-app 프로젝트명 --template typescript
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
yarn add typescript @types/node @types/react @types/react-dom @types/jest
npm i --save-dev @types/styled-component
npm i styled-components
ReactDOM.createRoot(document.getElementById('root'))
-> ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
로 변경(오류가 발생하면).ts
와 .tsx
의 차이 : .ts
는 typescript이며 .tsx
는 typescript + react 문법을 사용const value = event.currentTarget.value;
const tagName = event.currentTarget.tagName;
const width = event.currentTarget.width;
const id = event.currentTarget.id;
const {
currentTarget: {value, tagName, width, id} // event안 curentTarget안에 value의 값을 기존 이름 그대로 value, tagName, width, id 라는 변수를 만듦
} = event;
const plus = (a:number, b:number) => a + b;
plus(1,2) // 정상
plus("a", 2) // 오류
interface ContainerProps {
bgColor : string;
borderColor: string;
}
const Container = styled.div<ContainerProps>`
width:200px;
height:200px;
background-color: ${props => props.bgColor};
border-radius:100px;
border:5px solid ${props => props.borderColor}
`;
interface CircleProps {
bgColor : string;
borderColor?: string;
text?: string;
}
function Circle({bgColor, borderColor, text = "default text"}:CircleProps){
const [value, setValue] = useState<number|string>(0);
setValue(2);
setValue("hello");
// setValue(true); 에러
return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}> {text}</Container> // borderColor 가 없으면 bgColor로 사용
}
interface playerShape {
name:string;
age:number;
}
const sayHello = (playerObj:playerShape) => `Hello ${playerObj.name} you are ${playerObj.age} years old.`
sayHello({name:"hi", age:2})
sayHello({name:"gildong", age:100})
const [value, setValue] = useState("");
const onChange = (e:React.FormEvent<HTMLInputElement>) => {
const {currentTarget: {value}} = e;
setValue(value);
};
const onSubmit = (e:React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log("hello", value);
}
return (
<div>
<form onSubmit={onSubmit}>
<input type="text" placeholder='username' value={value} onChange={onChange}/>
<button>Log in</button>
</form>
</div>
);
npm i react-router-dom@5.3.0
npm i react-query
React Query
는 데이터 Fetching, 캐싱, 동기화, 서버 쪽 데이터 업데이트 등을 쉽게 만들어 주는 React 라이브러리<React.StrictMode>
제거// (함수)(); 를 사용하면 해당 로직을 바로 호출할 수 있음
(async() => {
fetch("https://api.coinpaprika.com/v1/coins");
})();
npm install recoil
yarn add recoil
npm install react-hook-form
register
: Object 반환. 입력 등록, 요소 선택, 유효성 검사 규칙을 React Hook Form에 적용할 수 있음watch
: state. 지정된 입력을 감시하고 해당 값을 반환handlerSubmit
: 인자 2개 필요. onValid(필수), inValid(선택). 양식 유효성 검사가 성공하면 양식 데이터를 수신formState
: 에러 반환.npm i react-beautiful-dnd
npm i --save-dev @types/react-beautiful-dnd
(HOC : Higer Order Component)
react memo
는 prop이 바뀌지 않는다면 컴포넌트를 렌더링 하지 않도록 하는 역할export default React.memo(DragabbleCard);
npm i gh-pages
: 결과물을 github pages에 업로드할 수 있게 해주는 패키지npm run build
: build 폴더 생성됨❗gh-pages로 배포 후 새로고침 시 404 에러 발생
- gh-pages는 SPA를 지원하지 않음
- https://jihye0526.github.io/react-master-final 라는 메인 사이트가 있을 경우 https://jihye0526.github.io/react-master-final/tv 와 같은 URL 을 인식하지 못하고 모두 404 page 로 뜨게 됨
public
폴더에404.html
을 만들어서 해당 URL 을 쿼리로 만들어서 리다이렉션- 해결방법
💡5.4.1 참고
const test = { "To Do" : ["a", "b"], Doing : [ "c", "d", "e"], Done : ["f"] } ---------------------------------------------------------- {...test, "To Do" : [1, 2, 3]} ---------------------------------------------------------- // 결과 { "To Do": [1, 2, 3], "Doing": ["c", "d", "e"], "Done": ["f"] }
Droppable
: droppableId(필수), Draggable
: draggableId(필수), Index(필수: 정렬순서)JavaScript
를 사용 할 때, 특정 DOM 을 선택해야 하는 상황에 getElementById, querySelector 같은 DOM Selector 함수를 사용해서 DOM 을 선택. 리액트
를 사용하는 프로젝트에서도 가끔씩 DOM 을 직접 선택해야 하는 상황이 발생 할 때 ref
라는 것을 사용function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
useRef
는 .current 프로퍼티로 전달된 인자(initialValue)로 초기화 된 변경 가능한 ref 객체를 반환npm install framer-motion
❗CRACO(Create React App Configuration Override)
CRACO(Create React App Configuration Override)
는 CRA에 config 설정을 덮어쓰기 위한 패키지- CRA에서
eject
를 하지 않아도 root 폴더에craco.config.js
를 추가해서 eslint, babel, postcss 등을 쉽게 설정가능- 설치 :
npm install @craco/craco --save
initial
: 초기 상태animate
: 변화 원하는 동작, transition 및 transition type 변경variants
: stage를 가지고 있고 animation을 좀 더 편리하게 사용할 수 있도록 도와줌. AnimatePresence
를 사용하면 구성 요소가 React 트리에서 제거될 때 애니메이션 효과를 볼 수 있음npm start
로 실행시키면 http://localhost:9000로 실행되며 인터넷 환경에 의해 화면이 보일수도 있고 안보일수도 있음npm run build
-> npm run serve
로 실행하면 http://localhost:9000으로 실행되며 나중에 인터넷 환경이 이상해지더라도 화면이 안보이는 경우가 없음npm start
로 실행시킨 화면은 바로 화면을 볼 수 있지만 npm run serve
로 실행시킨 화면은 서버를 껐다 켜야 볼 수 있음npm i -g gatsby-cli
gatsby new
💡참고
- 라이브러리? 개발자들이 불러오는 어떤 대상(import). 제어의 흐림이 개발자에게 있음 ex) React
- 프레임워크? 원하는 기능 구현에 집중하여 개발할 수 있도록 일정한 형태와 필요한 기능을 갖추고 있는 골격. 제어의 흐름이 프레임워크에 있음 ex) Vue, NextJS, Gatsby
query {
allPlanets {
totalCount
planets {
name
population
}
}
allFilms {
totalCount
films {
title
director
releaseDate
}
}
film(id:"ZmlsbXM6MQ==") {
title
producers
planetConnection {
planets {
name
}
}
speciesConnection {
species {
name
}
}
}
}
useStaticQuery
: 정적 쿼리 사용. useStaticQuery는 빌드 시 리액트 훅을 사용하여 Gatsby의 GraphQL 데이터 계층을 쿼리하는 기능을 제공. 이를 통해 React 컴포넌트는 구문 분석, 평가 및 컴포넌트에 삽일될 GraphQL 쿼리를 통해 데이터를 검색 할 수 있음