<React> 동적으로 CSS 적용하기, Styled-Components

·2023년 5월 6일
0

React

목록 보기
5/23

동적으로 CSS 적용하기

React에서 동적으로 CSS를 입히고 싶다면, 아래 예시코드처럼 state와 백틱을 활용하여 적용할 수 있다.

(생략 코드 ...)
const [isValid, setIsValid] = useState(true);
<div className={`form-control ${!isValid ? "invalid" : ""}`}>

state isValid의 true/false에 따라 invalid 클래스가 동적으로 적용된다.

  
import React, { useState } from "react";

import Button from "../../UI/Button/Button";
import "./CourseInput.css";

const CourseInput = (props) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [isValid, setIsValid] = useState(true);

  const goalInputChangeHandler = (event) => {
    setEnteredValue(event.target.value);
  };

  /** Form을 제출하는 함수. 빈값이면 텍스트 색상이 빨갛게 변경됩니다. */
  const formSubmitHandler = (event) => {
    event.preventDefault();
    if (enteredValue.trim().length === 0) {
      return setIsValid(false);
    }
    setIsValid(true);
    props.onAddGoal(enteredValue);
    setEnteredValue("");
  };

  return (
    <form onSubmit={formSubmitHandler}>
      <div className={`form-control ${!isValid ? "invalid" : ""}`}>
        <label>Course Goal</label>
        <input
          type="text"
          onChange={goalInputChangeHandler}
          value={enteredValue}
        />
      </div>
      <Button type="submit">Add Goal</Button>
    </form>
  );
};

export default CourseInput;

Styled-Components

스타일 컴포넌트의 기본 설정은 아래와 같다.

const Box = styled.div``

백틱 안에는 적용할 스타일을 지정해주면 된다.
그리고 가상 선택자를 적용할 때는 & 기호를 붙혀주면 된다.

스타일 컴포넌트는 해당 컴포넌트에서만 스타일이 적용되므로, 다른 컴포넌트에 스타일 영향을 끼치지 않는다. 스타일 컴포넌트별로 클래스 이름이 각각 고유하기 때문이다.

  // 스타일 컴포넌트 예시 코드
  const Button = styled.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;

  	&:focus {
    outline: none;
  	}

  	&:hover,
  	&:active {
    	background: #ac0e77;
    	border-color: #ac0e77;
    	box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
  	}
`;

0개의 댓글