LoginSignup
5
1

More than 3 years have passed since last update.

Styled-Componentsで::after、::beforeのcontentを動的に変更するときの注意

Posted at

タイトル通り。ハマるのでメモ。

component

任意のメッセージを疑似要素で表示するコンポーネントの例。

component
import React from "React";
import styled from "styled-components";

type Props = {
  className?: string;
  message: string;
}

const BaseComponent: React.FC<Props> = (props) => {
  return (
    <div className={props.className}>
      {props.children}
    </div>
  );
}

export const Component = styled(BaseComponent)`
  position: relative;
  &:before {
    content: "(ここをPropsの値で動的に変更したい)"
    ...略
  }
`

×

普通に受け渡せばうまくいく気がするが・・・
これはうまくいかない。
contentが正しい形ではないため、beforeの要素自体出現しない。

export const Component = styled(BaseComponent)<Pick<Props, "message">>`
  position: relative;
  &:before {
    content: ${({message}) => return message}
    ...略
  }
`

contentはクオーテーションで囲まれた文字である必要がある。
これだけで解決。

export const Component = styled(BaseComponent)<Pick<Props, "message">>`
  position: relative;
  &:before {
    content: "${({message}) => return message}"
    ...略
  }
`
5
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
5
1