html,css,js 공부/React

React css 적용방법

ari0930 2024. 3. 19. 15:08

1. 외부css 파일 사용하기 

<link rel="stylesheet" href="styles.css">

 

2. css 모듈 사용하기 

// Button.module.css
.button {
  background-color: blue;
  color: white;
}


// Button.js
import React from 'react';
import styles from './Button.module.css';

const Button = () => {
  return <button className={styles.button}>Click me</button>;
}

export default Button;

파일 이름을 ~~~.modul.css로 지정하여 css 모듈을 만들수 있다 

 

node-sass  를 이용하면 scss파일로 만들어서 위와 같은 방식으로 외부모듈로 사용할수 있다 
설치할때 터미널에 npm install node-sass 를 입력하면 설치가능하다 

 

scss 로지정하면 위와같은 모양으로 나탄다.

 

3. 인라인 스타일을 jsx 요소에 직접 입력하여 사용하기 

// App.js
import React from 'react';

const App = () => {
  return (
    <div style={{ backgroundColor: 'blue', color: 'white' }}>
      Hello, World!
    </div>
  );
}

export default App;

 

4. 라이브러리를 이용한 css 작성 하는방법 

Emotion 을 이용한 방법

npm install @emotion/react @emotion/styled 

/** @jsxImportSource @emotion/react */
import {jsx, css} from "@emotion/react";
import styled from "@emotion/styled";

export const Emotion = () =>{

    //scss 기술방법
    const containerStyle = css`
    border: solid 1px pink;
    border-radius: 40px;
    padding: 8px;
    margin: 8px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    `;

    //인라인 스타일 기술방법
    const titlestyle = css({
        margin: 0,
        color: "#aaa",
    });


    return (
        <div css={containerStyle} >
            <p css={titlestyle}>Emotion</p>
            <SButton>버튼</SButton>
        </div>
    );
};

//컴포넌트 로기술 import styled from "@emotion/styled"; 이걸 불러오ㅑ한다 
const SButton = styled.button`
background-color: pink;
border: none;
padding: 8px;
border-radius: 8px;
&:hover{
    background-color: #aaa;
    color: #fff;
    cursor: pointer;
}
`;
반응형