# Styled Componens
styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾
styled-components.com
- CSS파일을 따로 만들지 않고 자바스크립트에서 CSS를 사용하게 해주는 라이브러리
- CSS-JS 라이브러리 중에 제일 유명함
- 스타일이 첨부되는 현 컴포넌트에만 영향을 주고 다른 컴포넌트에는 영향을 미치지 못한다.
- 단점은 자바스크립트내에서 작성하기 때문에 코드가 보다 복잡해질 수 있다.
1. 홈페이지 접속

npm install --save styled-components 설치
2. 사용할 파일에 가서 임포트 해준다.
import styled from 'styled-components';
3. 우리가 적용하고자 하는 요소뒤에 백틱을 붙이고 백틱 안에 원하는 스타일을 적용 해주면 된다.
const Button = styled.button``;
예시코드
import styled from 'styled-components';
const Button = styled.button`
width: 100%;
font: inherit;
padding: 0.5rem 1.5rem;
border: 1px solid #8b005d;
color: white;
background: #8b005d;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
cursor: pointer;
@media (min-width: 768px) {
width: auto;
}
&:focus {
outline: none;
}
&:hover,
&:active {
background: #ac0e77;
border-color: #ac0e77;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
`;
// const Button = props => {
// return (
// <button type={props.type} className="button" onClick={props.onClick}>
// {props.children}
// </button>
// );
// };
export default Button;
- 이때 .button:focus 와 같이 가상선택자의 경우에는 패키지에서 지원하는 '&' 을 사용해주면 된다
- 가상 선택자를 사용하겠다고 패키지에 선언하는것과 같다.
- 미디어쿼리도 사용 가능!
또는
기존 클래스이름을 통해 스타일을 전달하던 방식에 사용할 수도 있다.
<div className={`form-control ${!isValid ? 'invalid' : ''}`}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</div>
import React, { useState } from 'react';
import styled from 'styled-components';
const FormControl = styled.div`
margin: 0.5rem 0;
& label {
font-weight: bold;
display: block;
margin-bottom: 0.5rem;
color: ${props => (props.invalid ? 'red' : 'black')};
}
& input {
display: block;
width: 100%;
border: 1px solid ${props => (props.invalid ? 'red' : '#ccc')};
background: ${props => (props.invalid ? '#ffd7d7' : 'transparent')};
font: inherit;
line-height: 1.5rem;
padding: 0 0.25rem;
}
& input:focus {
outline: none;
background: #fad0ec;
border-color: #8b005d;
}
`;
const CourseInput = props => {
const [enteredValue, setEnteredValue] = useState('');
const [isValid, setIsValid] = useState(true);
const goalInputChangeHandler = event => {
if (event.target.value.trim().length > 0) {
setIsValid(true);
}
setEnteredValue(event.target.value);
};
const formSubmitHandler = event => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
};
return (
<form onSubmit={formSubmitHandler}>
<FormControl invalid={!isValid}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</FormControl>
</form>
);
};
export default CourseInput;
- 대상으로 하고 싶은 중첩선택자가 있을 경우에도 '&'을 사용
- 바꾸고자 하는 요소에서 props값을 사용할 수 있다.
# CSS Module
Adding a CSS Modules Stylesheet | Create React App
Note: this feature is available with react-scripts@2.0.0 and higher.
create-react-app.dev
- create react app은 이미 해당 기능을 지원하고 있음
- 순수CSS로 기존 방법과 똑같이 사용하며 사용방법은 간단하다.
1. CSS파일명에 module을 붙여준다 → 예를들어 'Button.module.css'
2. CSS를 사용할 컴포넌트에 임포트 해준다.
import styles from './Button.module.css';
3. 클래스 이름을 지정해준다. (동적으로 지정 가능!)
className={`${styles['form-control']} ${!isValid && styles.invalid}`}
- CSS모듈은 내부적으로 클래스이름에 많은 정보가 추가된다.
- '컴포넌트이름_클래스이름_고유한 해시값'
- 모듈별로 고유한 값을 만들어 주기 때문에 이름이 충돌할 걱정없이 코딩할 수 있다.
📌참고
유데미 리액트 완벽가이드
'Front-end > HTML & CSS' 카테고리의 다른 글
[CSS] Grid로 배치하기 (0) | 2023.11.20 |
---|---|
[CSS] Flex로 정렬하기 (0) | 2023.11.16 |
[HTML] WAI-ARIA (0) | 2023.01.12 |
# Styled Componens
styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾
styled-components.com
- CSS파일을 따로 만들지 않고 자바스크립트에서 CSS를 사용하게 해주는 라이브러리
- CSS-JS 라이브러리 중에 제일 유명함
- 스타일이 첨부되는 현 컴포넌트에만 영향을 주고 다른 컴포넌트에는 영향을 미치지 못한다.
- 단점은 자바스크립트내에서 작성하기 때문에 코드가 보다 복잡해질 수 있다.
1. 홈페이지 접속

npm install --save styled-components 설치
2. 사용할 파일에 가서 임포트 해준다.
import styled from 'styled-components';
3. 우리가 적용하고자 하는 요소뒤에 백틱을 붙이고 백틱 안에 원하는 스타일을 적용 해주면 된다.
const Button = styled.button``;
예시코드
import styled from 'styled-components';
const Button = styled.button`
width: 100%;
font: inherit;
padding: 0.5rem 1.5rem;
border: 1px solid #8b005d;
color: white;
background: #8b005d;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
cursor: pointer;
@media (min-width: 768px) {
width: auto;
}
&:focus {
outline: none;
}
&:hover,
&:active {
background: #ac0e77;
border-color: #ac0e77;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
`;
// const Button = props => {
// return (
// <button type={props.type} className="button" onClick={props.onClick}>
// {props.children}
// </button>
// );
// };
export default Button;
- 이때 .button:focus 와 같이 가상선택자의 경우에는 패키지에서 지원하는 '&' 을 사용해주면 된다
- 가상 선택자를 사용하겠다고 패키지에 선언하는것과 같다.
- 미디어쿼리도 사용 가능!
또는
기존 클래스이름을 통해 스타일을 전달하던 방식에 사용할 수도 있다.
<div className={`form-control ${!isValid ? 'invalid' : ''}`}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</div>
import React, { useState } from 'react';
import styled from 'styled-components';
const FormControl = styled.div`
margin: 0.5rem 0;
& label {
font-weight: bold;
display: block;
margin-bottom: 0.5rem;
color: ${props => (props.invalid ? 'red' : 'black')};
}
& input {
display: block;
width: 100%;
border: 1px solid ${props => (props.invalid ? 'red' : '#ccc')};
background: ${props => (props.invalid ? '#ffd7d7' : 'transparent')};
font: inherit;
line-height: 1.5rem;
padding: 0 0.25rem;
}
& input:focus {
outline: none;
background: #fad0ec;
border-color: #8b005d;
}
`;
const CourseInput = props => {
const [enteredValue, setEnteredValue] = useState('');
const [isValid, setIsValid] = useState(true);
const goalInputChangeHandler = event => {
if (event.target.value.trim().length > 0) {
setIsValid(true);
}
setEnteredValue(event.target.value);
};
const formSubmitHandler = event => {
event.preventDefault();
if (enteredValue.trim().length === 0) {
setIsValid(false);
return;
}
props.onAddGoal(enteredValue);
};
return (
<form onSubmit={formSubmitHandler}>
<FormControl invalid={!isValid}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</FormControl>
</form>
);
};
export default CourseInput;
- 대상으로 하고 싶은 중첩선택자가 있을 경우에도 '&'을 사용
- 바꾸고자 하는 요소에서 props값을 사용할 수 있다.
# CSS Module
Adding a CSS Modules Stylesheet | Create React App
Note: this feature is available with react-scripts@2.0.0 and higher.
create-react-app.dev
- create react app은 이미 해당 기능을 지원하고 있음
- 순수CSS로 기존 방법과 똑같이 사용하며 사용방법은 간단하다.
1. CSS파일명에 module을 붙여준다 → 예를들어 'Button.module.css'
2. CSS를 사용할 컴포넌트에 임포트 해준다.
import styles from './Button.module.css';
3. 클래스 이름을 지정해준다. (동적으로 지정 가능!)
className={`${styles['form-control']} ${!isValid && styles.invalid}`}
- CSS모듈은 내부적으로 클래스이름에 많은 정보가 추가된다.
- '컴포넌트이름_클래스이름_고유한 해시값'
- 모듈별로 고유한 값을 만들어 주기 때문에 이름이 충돌할 걱정없이 코딩할 수 있다.
📌참고
유데미 리액트 완벽가이드
'Front-end > HTML & CSS' 카테고리의 다른 글
[CSS] Grid로 배치하기 (0) | 2023.11.20 |
---|---|
[CSS] Flex로 정렬하기 (0) | 2023.11.16 |
[HTML] WAI-ARIA (0) | 2023.01.12 |