Open2
React ✖️ Emotion で :nth-childを使用する🌟

React ✖️ Emotion で :nth-childを使用する🌟
- ReactのEmotionで:nth-child(even)セレクタを使用するには、Emotionのcss関数を使ってスタイルを定義して、その中で:nth-child(even)を指定します。
- 次のコードでは、css関数を使ってリストアイテムのスタイルを定義して、
&:nth-child(even)
を使って偶数番目のリストアイテムの背景色を変更しています。
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const listItemStyle = css`
&:nth-child(even) {
background-color: #f0f0f0; // 例として偶数のアイテムの背景色を灰色に設定
}
`;
const ListComponent = () => (
<ul>
<li css={listItemStyle}>Item 1</li>
<li css={listItemStyle}>Item 2</li>
<li css={listItemStyle}>Item 3</li>
<li css={listItemStyle}>Item 4</li>
</ul>
);
export default ListComponent;

emotion で The pseudo class ":nth-child" is potentially unsafe when doing server-side rendering. Try changing it to ":nth-of-type" エラー
- Next.js ✖️ Emotion の際に発生するエラー
- SSRだと、
:nth-child
が使えないことによるエラーらしい。 -
/* emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason */
を記述することで、エラーメッセージそのものは消えるらしい。
span:nth-child(2) /* emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason */ {
animation-delay: 0.2s;
}
span:nth-child(4) /* emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason */ {
animation-delay: 0.4s;
}
参考・引用