위처럼 생긴 버튼의 css를 리액트에서 여러가지 방법으로 구현할 수 있다.
import React from "react";
import "./Button.css";
const Button = (props) => {
return (
<button type={props.type} className="button" onClick={props.onClick}>
{props.children}
</button>
);
};
export default Button;
.button {
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;
}
.button:focus {
outline: none;
}
.button:hover,
.button:active {
background: #ac0e77;
border-color: #ac0e77;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
설치법
npm install --save styled-components
import styled from "styled-components";
const Button = styled.<태그명>`<css 내용>`;
import React from "react";
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);
}
`;
export default Button;
해당 컴포넌트 내에서만 작동하는 css이다
고유의 id를 가짐
import React from "react";
import styled from "styled-components";
const But = styled.button`
width: 100%;
font: inherit;
padding: 0.5rem 1.5rem;
border: 1px solid #8b005d;
color: white;
background: ${(props) => (props.invalid ? "#8b005d" : "#ccc")};
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 <But invalid={props.isValid}>{props.children}</But>;
};
export default Button;
내부에 함수를 선언하여 동적인 styled을 줄 수 있다.
고유의 id를 가짐
name.css
파일을 name.module.css
로 변경import styles from "./Button.module.css";
로 호ㅜㅊㄹimport React from "react";
import styles from "./Button.module.css";
const Button = (props) => {
return (
<button type={props.type} className={styles.button} onClick={props.onClick}>
{props.children}
</button>
);
};
export default Button;
import React from "react";
import styles from "./Button.module.css";
const Button = (props) => {
return (
<button
type={props.type}
className={`${styles["button"]} ${!props.isValid && styles.invalid}`}
onClick={props.onClick}
>
{props.children}
</button>
);
};
export default Button;