본문 바로가기

styled-components

Button 만들어보기

이 포스트는 Udemy 사이트에 올라 온 Tom Phillips의 "React styled-components v5 (2021 edition)" 강의를 듣고 정리한 것입니다.

 

🔗링크

https://www.udemy.com/course/react-styled-components/

 

React styled components v5 (2021 edition)

Ditch CSS stylesheets! Learn CSS in JS to quickly and cleanly style React components with the styled components library

www.udemy.com

 

 

 

🌞 현재 폴더 구조

현재 폴더 구조

 

src 폴더의 components 폴더 아래 App.js 파일, common 폴더, pages 폴더가 있다.

common 폴더 아래에 index.js와 Button.js 파일을 만들었다.

 

 

 

 

🌞 common > Button.js

import styled from "styled-components";

const Button = styled.button`
	display: block;
	width: 100%;
	color: white;
	background-color: #f8049c;
	font-size: 1em;
	font-weight: bold;
	padding: 8px;
	border-radius: 4px;
	border: none;
	box-shadow: none;
	white-space: none;

	&:disabled {
		background: #eee;
		color: #666;
	}
`;

export { Button };

 

Button.js 파일의 코드.

styled-components만 만들어서 export할 것이기 때문에 따로 React를 import하지 않았다.

(사실 최근 리액트 버전에서부터는 컴포넌트에 굳이 import React from "react"코드를 넣을 필요가 없기는 하다. )

 

export default Button; 대신에 export { Button };으로 named export를 한다.

 

 

 

 

 

🌞 common > index.js

그리고 common 폴더에 있는 index.js에서

 

export * from "./Button";

Button 파일에 있는 모든 것을 export하고 

 

 

 

 

 

🌞 components > App.js

components 폴더에 있는 App.js로 와서

 

import { Button } from "components/common";

function App() {
	return (
		<>
			<h1>App.js</h1>
			<Button>Test</Button>
		</>
	);
}

export default App;

 

버튼을 import 할 때, import { Button } from "components/common"; 이렇게 작성하면 된다.

 

 

참고)

1. 중괄호 빼먹으면 당연히 오류난다

2. import 해주는 경로에  "../.../" 가 없는 이유는 jsconfig.json 설정 때문 

 

{
    "compilerOptions": {
        "baseUrl": "src"
    },
    "include":["src"]
}

 

 

 

 

💻 현재 상태