Web/React
[React] JSX 다루기(2)
s00ng
2022. 7. 18. 00:11
JSX Styling
1) inline Styling
- style 속성에 들어가는 값은 객체형태
- css 속성이름이 camelCase로 작성되어 있음
- style 값에 들어갈 객체 미리 선언 가능
- Hello.jsx
import React from "react"; //React 컴포넌트라서
/* Hello라는 함수형 컴포넌트 생성 */
function Hello(){
const PracticeStyle = {
marginTop: '10px',
backgroundColor:'blue'
};
return (
<>
<div style={PracticeStyle}>Hello World!</div>
<div style={PracticeStyle}>Hello World!</div>
<div style={PracticeStyle}>Hello World!</div>
</>
);
}
export default Hello;
2) CSS 파일 작성
- 기존의 css 파일 작성하는 방식 사용 가능
- Hello.css
.red {
background-color: red;
color:beige;
font-size: 48px;
padding: 16px;
}
- Hello.jsx
import React from "react"; //React 컴포넌트라서
import "./Hello.css"
/* Hello라는 함수형 컴포넌트 생성 */
function Hello(){
const PracticeStyle = {
marginTop: '10px',
backgroundColor:'blue'
};
return (
<>
<div className = 'red'>Hello World!</div>
<div className = 'red'>Hello World!</div>
<div className = 'red'>Hello World!</div>
</>
);
}
export default Hello;
3. Styled Component
- 개발자들이 선호하는 CSS인 JS 라이브러리 중 하나
- javscript 내에서 스타일링을 돕는 라이브러리
- jsx에서 css를 그대로 사용할 수 있음
→ 라이브러리 설치 필요 (VSCode terminal)
yarn add styled-components
(* package.json에서 라이브러리가 추가된 것을 확인할 수 있음)
→ 이로써 스타일링된 컴포넌트를 만들수 있음
→ React 에서 Component 이름은 대문자로 시작해야함
- Hello.jsx
import React from "react"; //React 컴포넌트라서
import styled from 'styled-components' // styled-components를 줄여서 styled로 함
/* Hello라는 함수형 컴포넌트 생성 */
function Hello(){
const StyledButton = styled.button`
color:red;
background-color:gray;
`
return (
<StyledButton>나만의 버튼</StyledButton>
);
}
export default Hello;
→ styled.button이 반환하여 StyledButton에 들어가는 것은 React Component
→ button 형태의 React Component를 받아와서 커스텀하는 느낌