目的
テンプレートリテラルを用いて、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'));
解説
- コンポーネントを使用すると、
isHighlighted
がtrue
の場合、highlight
クラスが追加されます。 - つまり、
isHighlighted
がtrue
の時に赤いボーダーが表示され、false
の時にはボーダーが表示されません。