[ReactJS_MasterClass] #2 STYLED COMPONENTS

유은선·2023년 1월 18일
0

ReactJS_MasterClass

목록 보기
1/11
post-thumbnail

✍2.0 Why styled Components

1. cmd창에 코드 한줄만 입력하면 프로젝트 생성 완료

npx create-react-app (프로젝트명)

2. cmd창에서 바로 vscode 실행

code (프로젝트명)

3. 페이지 실행

npm start

4. App.js와 index.js 제외하고 src에 있는 파일들 삭제, App.js와 index.js의 코드 수정 필요

index.js

function App() {
  return (
    <div>
      <h1>Welcome back!</h1>
    </div>
  );
}

export default App;

✍2.1 Our First Styled Component

스타일 컴포넌트 설치

npm i styled-components

``를 백틱(back tick) 이라고 하는데, 이 내부에 css 코드를 적어서 스타일을 적용할 수 있다.

const Father = styled.div``;

styled-component를 사용하면 style구현부분으로 나누어 코드 작성이 가능

✍2.2 Adapting and Extending

2.1에서 BoxOne과 BoxTwo는 background-color만 제외하고 거의 모든 것이 일치했다.

2.2에서는 어떻게하면 컴포넌트를 설정 변경이 가능한 형태로 만들 수 있는지(컴포넌트를 확장하는 방법)에 대해 배워본다!

✔️1. props를 통해 컴포넌트를 설정하기
→ 컴포넌트를 변경 가능하게 만드는 방법 (속성 값 바꾸기)

const Box = styled.div`
  background-color: ${(props) => props.bgColor};
  width: 100px;
  height: 100px;
`;

✔️2. 컴포넌트를 통해서 새로운 컴포넌트를 만들어 내기 (컴포넌트 확장)
→ 기존 컴포넌트의 모든 것을 가져와서 새로운 것들을 더한다.

const Circle = styled(Box)`
  border-radius: 50px;
`;

✍2.3 'As' and Attrs

✔️1. 컴포넌트의 태그를 바꾸고 싶은데 스타일은 바꾸고 싶지 않을 때 : As

const Btn = styled.button`
  color: white;
  background-color: tomato;
  border: 0;
  border-radius: 15px;
`;

<Btn as="a">Log in</Btn>

✔️2. HTML 태그의 속성을 설정할 수 있다.

<Father>
<Input required/>
<Input required/>
<Input required/>
<Input required/>
</Father>

const Input = styled.input.attrs({ required: true, minLength: 10 })`
  background-color: blue;
`;

예를들어, input이 이렇게 많으면 하나하나 required를 적어줘야 하는데,
styled components에서는 컴포넌트를 생성할 때, 속성값을 설정할 수 있게 해준다.

✍2.4 Animations and Pseudo Selectors

styled components의 animation을 주기 위해 helper function을 import 해준다.

import styled,{keyframes} from "styled-components";

Box안의 span을 선택하는 방법이 있다. (Box안의 span을 target)
즉, 모든 component에 styled component 처리를 해 줄 필요는 없다는 사실!

const Box = styled.div`
  span {
    font-size: 36px;
  }
`;
<Box>
    <span>😋</span>
</Box>

:hover 처리도 가능하다.

여기서 span { &:hover } 나, span 바깥에서 span:hover를 하는것은 서로 같다.

span {
   font-size: 36px;
   &:hover {
     font-size: 48px;
   }
 }
 
span:hover{
   font-size: 48px;
}

✍2.5 Pseudo Selectors part Two

styled components안의 element를 선택하는 다른 방법을 알아보자.
2.4에 이어서, span을 p로 바꾸면 font-size 효과가 적용되지 않는다. tag name에 의존하고 있기 때문!

태그에 의존하고 싶지 않은 경우 styled component를 만들어 해결해 주면 된다.
Box 컴포넌트 안에 Emoji 컴포넌트를 직접적으로 타겟팅 → Emoji가 span이든 p이든 div든 상관없이 쓸 수 있다.

const Box = styled.div`
 ${Emoji}:hover {
   font-size: 98px;
 }
`;

✍2.7 Themes

theme이란? 기본적으로 모든 색상들을 가지고 있는 object

ThemeProvider를 styled-components로 부터 import 해야한다. 이 때, prop 하나가 필요하다.

index.js

import { ThemeProvider } from "styled-components";

const darkTheme = {
  textColor: "whitesmoke",
  backgroundColor: "#111",
};

const lightTheme = {
  textColor: "#111",
  backgroundColor: "whitesmoke",
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

여기서 Title이 App 컴포넌트 안에 있고, App은 ThemeProvider안에 있기 때문에
내 Title이 Theme object에 접근해서 textColor를 얻을 수 있는 것이다. (Wrapper도 마찬가지)

darkTheme 과 lightTheme의 textColor와 backgroundColor 이름이 같아야하는 이유(똑같은property 이름)는 darkTheme에서 lightTheme으로 변경해줄것이기 때문이다.
theme={lightTheme}으로 바꾸면 다른색이 바로 적용!

따라서, 정리해보자면 두개의 theme을 만들고 이 두개의 theme이 동일한 property 이름을 갖고 있다면, theme을 전환해줄 때 component를 따로 바꿔줄 필요가 없다.

profile
뭐든지 난 열심히 하지

0개의 댓글