반응형

Connect Typescript with styled-components

1. 설치

npm install @types/styled-components

2.  선언파일 만들기 (Create a declarations file)

src폴더 안에 styled.d.ts 생성 후 styled-components의 공식문서에서 선언파일 만드는 방법을 찾아 붙이기

//styled.d.ts

// import original module declarations
import "styled-components";

// and extend them!
declare module "styled-components" {
  export interface DefaultTheme {
    textColor: string;
    bgColor: string;
    btnColor: string;
  }
}
//theme.ts
import {DefaultTheme} from "styled-components/dist/types";

export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "black",
  btnColor: "teal",
};
export const darkTheme: DefaultTheme = {
  bgColor: "black",
  textColor: "white",
  btnColor: "tomato",
};
//App.tsx

import React, {useState} from "react";
import styled from "styled-components";

const Btn = styled.button`
  background-color: ${(props) => props.theme.btnColor};
`;

function App() {
  const [val, setVal] = useState("");
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    /** event의 타입을 주기위해서는 위와 같이 작성해야하는데 저것을 찾기 위해서는 어떤곳에서 이벤트가 이루어졌는지 생각해보면 쉽게 다가갈수 있음 혹은
     * 공식문서나 구글링을 통해 찾는 걸 추천함 */
    // console.log(event.currentTarget.value);
    /** 또한 보통 자바스크립트 같은 경우엔 target이라고 작성하는데 타입스크립트와 리액트를 같이 사용하는데 있어서 currentTarget으로 작성해야한다.*/
    const {
      currentTarget: {value},
    } = event;
    setVal(value);
  };

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log(val);
  };
  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          value={val}
          onChange={onChange}
          type="text"
          placeholder="UserName"
        />
        <button>Log In</button>
      </form>
      <Btn>눌러뽕</Btn>
    </div>
  );
}

export default App;

 

Styled-Components 의 Style - Reset 하기

  • npm i styled-reset
  • 아니면 styled-reset의 깃에 들어가 src/index.ts를 복붙하면됨
import React from "react";
import styled, {createGlobalStyle} from "styled-components";
import Mainpage from "./views/Mainpage";

const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@100;200;300;400;500;600;700&display=swap');
  html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, menu, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
main, menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, main, menu, nav, section {
  display: block;
}
/* HTML5 hidden-attribute fix for newer browsers */
*[hidden] {
    display: none;
}
body {
  line-height: 1;
  font-family: 'IBM Plex Sans KR', sans-serif;
  color: ${(props) => props.theme.textColor};
  background-color: ${(props) => props.theme.bgColor};
}
menu, ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
*{
  box-sizing:border-box;
}
a{
  text-decoration:none;
}
`;

const Wrapper = styled.div`
  display: flex;
`;
function App() {
  return (
    // Fragment - ghost component
    <>
      <GlobalStyle />
      <Wrapper>
        <Mainpage />
      </Wrapper>
    </>
  );
}

export default App;
728x90

'React > Styled-Components' 카테고리의 다른 글

2023/08/24__Styled-Components(2)  (0) 2023.08.24
2023/08/23__Styled-Components(1)  (0) 2023.08.23
반응형

1. Animation 과 Pseudo 선택자

//animation 효과를 주기위서는 keyframes를 불러와야한다.
import styled, {keyframes} from "styled-components";

const Wrapper = styled.div`
  display: flex;
`;

const rotateAnimation = keyframes`
0%{
transform:rotate(0deg);
border-radius:0px
}
50%{
  border-radius:100px;
}
100%{
transform:rotate(360deg);
border-radius:0px
}
`;

const Emoji = styled.span`
  font-size: 50px;
`;

const Box = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  background-color: tomato;
  animation: ${rotateAnimation} 3s linear infinite;
  span {
    font-size: 20px;
    &:hover {
      font-size: 60px;
      transition: ease-in-out 1s;
    }
    // SCSS와 비슷하다
  }
`;
const Box2 = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  background-color: tomato;
  animation: ${rotateAnimation} 3s linear infinite;

  ${Emoji}:hover {
    font-size: 100px;
    transition: ease-in-out 1s;
  }
`;

function App() {
  return (
    <Wrapper>
      <Box>
        <span>😀</span>
      </Box>
      <Box2>
        <Emoji>🥸</Emoji>
      </Box2>
      <Emoji>🥸</Emoji>
    </Wrapper>
  );
}

export default App;

2. Themes

다크모드를 하기 위한 첫단계

각 Theme에는 같은 오브젝트의 명이 담겨져 있어야한다고 생각하고 작업에 임하라.

//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: "#222",
};
const lightTheme = {
  textColor: "#222",
  backgroundColor: "whitesmoke",
};

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



//App.js
//animation 효과를 주기위서는 keyframes를 불러와야한다.
import styled, {keyframes} from "styled-components";

const Wrapper = styled.div`
  display: flex;
  background-color: ${(props) => props.theme.backgroundColor};
`;

const Title = styled.h1`
  color: ${(props) => props.theme.textColor};
`;
function App() {
  return (
    <Wrapper>
      <Title>HELLO</Title>
    </Wrapper>
  );
}

export default App;

 

728x90

'React > Styled-Components' 카테고리의 다른 글

2023/08/25__Styled-Components with Typescript(3)  (0) 2023.08.25
2023/08/23__Styled-Components(1)  (0) 2023.08.23
반응형

Styled-Components

React에서 style을 주기위한 방법은 몇가지가 있다.

  • 첫 번째로 직접 엘리멘탈에 스타일을 주는방법
return(
	<div style={{backgroundColor:'red'}}>
    	<h1>hello</h1>
    </div>
)
  • 두 번째로 CSS 모듈 파일을 만든다
  • 파일이름.module.css
import styles from '파일이름.module.css'

export default function 컴포넌트이름 (){
	return (
    	<div className={styles.hello}>
        	<h1 className={styles.text}> hello </h1>
        </div>
    )
}


/** 
파일이름.module.css

.hello{
background-color:teal;
}

.text {
color:white;
}

*/
  • 세 번째로는 프레임워크를 사용하는것
  • 네 번째로는 stlyed-component라이브러리를 사용

설치

리액트 프로젝트 생성 후

npm i styled-components
import styled from 'styled-compoenets'

//백틱에 스타일이 들어가야 한다.
const SayHello = styled.h1`
	background-color:teal;
	color:red;
    width:100px;
    height:100px
    `;
    
//props로도 스타일을 줄 수 있다.    
const SayMeetYou = styled.div`
	background-color: ${(props)=>props.bgColor};
    width:100px;
    heigth:100px;
    `;
    
// SayMeetYou의 요소를 그대로 사용하며 border-radius의 값을 추가하여 사용할 수 있다.
const SayBye = styled(SayMeetYou)`
    border-radius:50px;
    `;


// 예로 버튼태그에 스타일을 주었는데 링크테그에도 똑같은 스타일을 주고 싶을 때 사용하는 방법
const Btn = styled.button`
	border: 0;
    border-radius: 25px
    background-color: tomato:
    color:white;
    `;
    
//어트리뷰트 값도 지정해줄 수 있다.
const Input = styled.input.attrs({required:true, minLength:'10'})`
	background-color: cornflowerblue;
`;

export default function App (){
  return(
   <div>
    <div
     style={{ backgroundColor:'teal', width:100, height:100 }}>
				<h1> hello </h1>
    </div>
    <div>
     <SayHello> hello </SayHello>
    </div>
    <SayMeetYou bgColor={"orange"}}></SayMeetYou>
    <SayBye bgColor={"Yellow"}}></SayBye>
    <Btn>Click me</Btn>
    // Btn 스타일일을 쓰고 싶지만 링크로써 사용하고 싶다면 as라는 props를 줘서 원하는 html을 부여할 수 있다.
    <Btn as='a' href='URL LINK'>Click me</Btn>
    <Input/>
   </div>
  )
}

 

728x90

'React > Styled-Components' 카테고리의 다른 글

2023/08/25__Styled-Components with Typescript(3)  (0) 2023.08.25
2023/08/24__Styled-Components(2)  (0) 2023.08.24

+ Recent posts