LoginSignup
0
0

[CSS] [React] テンプレートリテラルを用いた2つのクラスを付与する方法

Last updated at Posted at 2024-06-16

目的

テンプレートリテラルを用いて、classNameに2つのクラスを付与する方法を記載

目次

基本構文(CSSファイル)

Example.css
.container {
  background-color: lightblue;
  padding: 20px;
  border-radius: 8px;
}

.highlight {
  border: 2px solid red;
}

解説

  • containerクラスは背景色、パディング、および角丸のスタイルを定義しています。
  • highlightクラスは赤いボーダーを定義しています。

基本構文(JSXファイル)

Example.jsx
import React from 'react';
import './Example.css';

const MyComponent = ({ isHighlighted }) => {
  return (
    <div className={`container${isHighlighted ? 'highlight' : ''}`}>
      This is a styled component.
    </div>
  );
};

export default MyComponent;

解説

  • xstyles.cssをインポートします。
  • isHighlightedというプロパティに基づいて、コンポーネントにhighlightクラスを追加するかどうかを決定します。
  • テンプレートリテラルを使用して、containerクラスにhighlightクラスを動的に追加しています。

※テンプレートリテラルを使用しない場合

Example.jsx
import React from 'react';
import './Example.css';

const MyComponent = ({ isHighlighted }) => {
  return (
    <div className={isHighlighted ? 'container highlight' : 'container'}>
      This is a styled component.
    </div>
  );
};

export default MyComponent;

活用例

上記のjsxファイルの活用例を示します。

JavaScript
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './Example.jsx';

const App = () => {
  return (
    <div>
      <MyComponent isHighlighted={true} />
      <MyComponent isHighlighted={false} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

解説

  • コンポーネントを使用すると、isHighlightedtrueの場合、highlightクラスが追加されます。
  • つまり、isHighlightedtrueの時に赤いボーダーが表示され、falseの時にはボーダーが表示されません。

参考リンク

0
0
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
0