React

React 10-3 Styled Component(theme)

와라리요 2023. 3. 1. 18:28

theme

 - theme는 최상단 파일에 스타일 값을 미리 설정한 후 자식 파일 또는 컨퍼넌트에 함수로 호출하여 값을 적용 시키기 위한 기능이다. 사용한 예로는 다크모드가 있다.

 

  import로

import { ThemeProvider } from 'styled-components';

 

  선언할 후 자신이 원하는 변수면으로 스타일 값을 설정한다. 이때는 기존에 사용하던 css의 프로퍼티가 아니기 때문에 잘 알아보고 사용하자!!

예)

const darkTheme = {
  textColor: "whitesmoke",
  backgroundColor: "#111",
}

 

  그 후 자신이 적용하고 싶은 컨퍼넌트에 부모 컨퍼넌트로 ThemeProvider를 선언한 후 theme 프롭스로 변수명을 선언한다.

예)

    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>

 

  자식 컨퍼넌트 파일로 이동해 css에 ${p => p.theme.css프러퍼티}를 선언하면 적용이 된다.

예)

const Title = styled.h1`
  color: ${p => p.theme.textColor};
`

 

  위의 예시 내용을 종합한 코드입니다.

//index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ThemeProvider } from 'styled-components';
import App from './App';


const darkTheme = {
  textColor: "whitesmoke",
  backgroundColor: "#111",
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);
// App.js

import styled from 'styled-components';

function App() {
  return (
      <Box>
        <Title>와라라라</Title>
      </Box>
  );
}
export default App;

const Box = styled.div`
  height: 98vh;
  width: 98vw;
  background-color: ${p => p.theme.backgroundColor};
  display: flex;
  justify-content: center;
  align-items: center;
`;

const Title = styled.h1`
  color: ${p => p.theme.textColor};
`