9

I somehow have to programmatically set the width of the :before for a div.

<div className="something" style={someStyle}> </div>

How can I define the someStyle so that the width of the :before of .something``div can change accordingly??

kojow7
  • 10,308
  • 17
  • 80
  • 135
Hao
  • 1,476
  • 3
  • 15
  • 20
  • 2
    Pseudo elements cannot be styled with inline styles as explained in http://stackoverflow.com/a/14141821/368697. You will have to style the `something` class name in a stylesheet with the `.something:before` selector. This is not a limitation of React but rather a design choice for HTML + CSS. – Ross Allen Sep 27 '14 at 08:30

3 Answers3

29

Yes, you can programmatically change the value of pseudo-elements like ::before, ::after in react.

Here is a trick.

app.js

const widthVar = 34;
const someStyle = {
     "--width": widthVar
}
<div className="something" style={someStyle}> </div>

style.css

.something:before{
      width: var(--width),
      // remaining code
}
am2505
  • 2,194
  • 15
  • 19
  • 1
    This one is actually good. I was looking for it, thank you. – uhetz Jan 13 '21 at 11:40
  • @uhetz I am really glad you like this solution. Yesterday I was also figuring out any solution but none of them works for me. – am2505 Jan 13 '21 at 12:24
  • 2
    If you're using Typescript, you'll need to extend the CSSProperties type from React before accessing the variable to make this work. See https://stackoverflow.com/a/65959390/868724 – aboutaaron Feb 24 '21 at 01:55
  • You saved me a considerable amount of time, thank you – Maxime Dec 02 '22 at 08:18
9

Pseudo elements cannot be styled with inline styles as explained in https://stackoverflow.com/a/14141821/368697. You will have to style the something class name in a stylesheet with the .something:before selector. This is not a limitation of React but rather a design choice for HTML + CSS.

If you need to programmatically change the width of the pseudo :before element, it is probably more appropriate as a regular DOM element rendered by React.

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
1

I got insight from @am2505 to use CSS variables as it helped me however, this way avoids inline styling.

HTML
<div className="something"> </div>

CSS

:root {
--width: <yourDefaultValue>
}

.something:before{
      width: var(--width),
}

JS

const changeWidth=() => {
    let root = document.querySelector(':root');
      root.style.setProperty('--width', '<yourNewValue>px');
   

call the function at the event you want the width to change. The changeWidth function can be further modified to dynamically work with state using conditional statements.

BrunoElo
  • 360
  • 6
  • 11