LoginSignup
0
1

More than 3 years have passed since last update.

Styled-componentsのお勉強 (React)

Posted at

Styled-componentsを使って、Reactでカスタムボタンを作成してみた。

CODESANDBOXを使った簡単なサンプルはこちら。

image.png

Custom Buttonを作成

App.js

import CustomButton from "./components/CustomButton.component";

function App() {
  return (
    <div className="App">
      <h1>Let's Build Custom Buttons!</h1>

      <p>Basic Button Theme</p>
      <CustomButton onClick={() => {console.log('You have become a member!!')}}> Become a member </CustomButton>

      <p>Inverted Theme</p>
      <CustomButton inverted> Subscribe </CustomButton>

      <p>Large Size</p>
      <CustomButton large> Styled-components </CustomButton>
    </div>
  );
}

手順

まずはCustom Buttonというコンポーネントを作成します。
内容は下記の通り・・・。

CustomButton.component
import React from "react";

import { ButtonContainer } from "./CustomButton.styles";

const CustomButton = ({ children, ...otherProps }) => {
  return <ButtonContainer {...otherProps}> {children} </ButtonContainer>;
};

export default CustomButton;

ButtonContainerはstyled-componentsのスタイリング名です。

  • まずはボタンの名称を{children}で受け取ります。
  • その他を...otherPropsとし、複数のPropsを受け取れるようにします(ES6文法)

このotherPropsとして受け取ったプロパティーはどのように使用されるか・・・
これは下記の通り。

CustomButton.styles
import styled, { css } from "styled-components";

const invertedStyles = css`
  background-color: #065fd4;
  color: #fff;
`;

const largeStyles = css`
  width: 200px;
  height: 80px;
  font-size: 18px;
`;

const getStyles = props => {
  if (props.inverted) {
    return invertedStyles;
  }

  if (props.large) {
    return largeStyles;
  }
};

export const ButtonContainer = styled.button`
  width: 150px;
  height: 50px;

  background-color: #ffffff;
  color: #065fd4;

  border: 1px solid #065fd4;
  font-size: 14px;

  outline: none;
  cursor: pointer;

  ${getStyles}
`;

ベースとなるButtonContainerでボタンのスタイリングを行い、${getStyles}でPropsの内容によってスタイリングを切り替えるようにしています。

もし、propsがinvertedなら、invertedStylesを適用させる、といった感じですね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1