React 나 CRA 가 아닌 별도의 Library 를 이용해서 스타일링한다.
Scope 오염을 최대한 방지, 다른 Style 이 방해를 놓지 않는다.
대표적으로 Styled Componets 와 emotion Lib 가 있다.
$ create-react-app 파일이름
$ npm i styled-components
Styled Button 하나를 만들어서 여러가지를 해보자.
// StyledButton.jsx
import styled, { css } from 'styled-components';
// styled-components 에 의해서 style 이 먹혀진 button 을 가져오라.
// styled.사용하려는 태그이름
const StyledButton = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0 1em;
padding: 0.25em 1em;
font-size: 20px;
${props => props.primary &&
css`
background: palevioletred;
color: white;
`}
`;
export default StyledButton;
// StyledA.jsx
import styled from 'styled-components';
// 기본적으로 새창에서 열리게 attrs 로 세팅해준다.
const StyledA = styled.a.attrs(props=>({
target: "_BLANK",
}))`
color: ${(props) => props.color}
`;
export default StyledA;
// App.js
import logo from './logo.svg';
import './App.css';
import StyledButton from './components/StyledButton';
import styled, { createGlobalStyle } from 'styled-components';
import StyledA from './components/StyledA';
const PrimaryStyledButton = styled(StyledButton)`
background: palevioletred;
color: black;
`;
const UppercaseButton = props => <button {...props} children={props.children.toUpperCase()}/>
const MyButton = props => <button className={props.className} children={`MyButton ${props.children}`}/>
const StyledMyButton = styled(MyButton)`
background: transparent;
border-radius: 3px;
border: 2px solid ${props => props.color || "palevioletred"};
color: ${props => props.color || "palevioletred"};
margin: 0 1em;
padding: 0.25em 1em;
font-size: ${props => props.fontSize || "20px" };
:hover {
border: 2px solid red;
}
::before {
content: "@";
}
`;
const GlobalStyle = createGlobalStyle`
button {
color: royalblue;
}
`;
function App() {
return (
<div className="App">
<GlobalStyle />
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
<StyledButton>버튼</StyledButton>
<StyledButton primary>버튼-primary</StyledButton>
<PrimaryStyledButton >PrimaryStyledButton</PrimaryStyledButton>
{/* as는 다른 tag로 사용하고 싶을때! as="a" 로 a tag로 사용이 가능하다. */}
<StyledButton as="a" href="/">버튼</StyledButton>
<StyledButton as={UppercaseButton}>button</StyledButton>
<StyledMyButton>button</StyledMyButton>
<StyledMyButton color="green" fontSize="100px">button</StyledMyButton>
<StyledA href="<https://google.com>">태그</StyledA>
</p>
</header>
</div>
);
}
export default App;