LoginSignup
5
2

More than 5 years have passed since last update.

Reactで複数クラスを適用する方法

Last updated at Posted at 2017-12-21

複数classNameの適用

classnamesをインストール(react-starter-kitにはインストール済み)

yarn add classnames --save

classnamesをインポート

import ClassNames from 'classnames';

true,falseで適用するclassNameを決定

const classNames = ClassNames({
    [s.button]: true,
    [s.buttonColor]: this.state.isBlue,
    [s.buttonSize]: this.state.isBig,
});

ボタン押下で適用クラスが切り替えられるサンプル

Home.js
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import ClassNames from 'classnames';
import s from './Home.css';

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isBlue: true,
      isBig: true,
    };
  }

  colorChange = () => {
    this.setState({ isBlue: !this.state.isBlue });
  };

  sizeChange = () => {
    this.setState({ isBig: !this.state.isBig });
  };

  render() {
    const classNames = ClassNames({
      [s.button]: true,
      [s.buttonColor]: this.state.isBlue,
      [s.buttonSize]: this.state.isBig,
    });

    return (
      <div className={s.root}>
        <input
          type={'button'}
          className={classNames}
          value={this.state.isBlue ? 'none' : 'blue'}
          onClick={() => this.colorChange()}
        />
        <input
          type={'button'}
          className={classNames}
          value={this.state.isBig ? 'small' : 'big'}
          onClick={() => this.sizeChange()}
        />
      </div>
    );
  }
}

export default withStyles(s)(Home);
Home.css
.root {
  padding-left: 20px;
  padding-right: 20px;
}

.button {
  height: 30px;
  width: 60px;
}

.buttonColor {
  background: #6688ff;
}

.buttonSize {
  height: 60px; 
  width: 80px;
}
5
2
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
5
2