0

I can't figure out how to make :before render in the DOM.

I tried this:

const inline = {
    backgroundColor: "yellow",
    width: "100px",
    height: "30px",
    display: "inline-block",
    position: "relative",
    "&::before": {
        content: '"Good Day"',
        position: "absolute",
        left: "-50px",
        top: "50px",
    },
}

return (
    <p style={style}>
        Lorem ipsum dolor sit amet, <i style={inline}></i>consectetur
        adipiscing elit, sed do<i style={inline}></i> eiusmod tempor
        incididunt ut labore et dolore magna aliqua.
        <i style={inline}></i>
    </p>
)

the styling of the i elements works as expected, except for the :before that is not rendered.

Any tip on how t accomplish this would be much appreciated

  • The link takes me to a new, default React app... – David Mar 30 '23 at 18:29
  • 2
    The ampersand is a part of SCSS/SASS/LESS, not the raw CSS that React can understand. There is no syntax that allows ":before" applied as an inline style, as in [this SO answer](https://stackoverflow.com/q/14141374/1426891). – Jeff Bowman Mar 30 '23 at 18:31

2 Answers2

1
const inline = { /* ... */
    "&::before": { /* ... */ },
}

The ampersand ("parent selector") is a part of SCSS/SASS/LESS, not the raw CSS properties that React can understand.

There is no syntax that allows ":before" applied as an inline style, as in this SO answer, nor through JavaScript manipulation as in this SO answer.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
1

Inline css styles do not support pseudo elements (they are not part of the element itself). The only way to apply style to pseudo elements is using css declarations (eg: setting an id and setup a css declaration with #id::before{ }).

One option for reactjs components is to use an explicit tag that works like :before (or :after) pseudo element, adding it to the start or end of the element content. Eg:

const inline = {
    backgroundColor: "yellow",
    width: "100px",
    height: "30px",
    display: "inline-block",
    position: "relative",
}

const before = {
        position: "absolute",
        left: "-50px",
        top: "50px",
}

return (
    <p style={style}>
        Lorem ipsum dolor sit amet, <i style={inline}></i>consectetur
        adipiscing elit, sed do<i style={inline}></i> eiusmod tempor
        incididunt ut labore et dolore magna aliqua.
        <i style={inline}><div style={before}>"Good Day"</div>Content</i>
    </p>
)
F.Igor
  • 4,119
  • 1
  • 18
  • 26