Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Reactjs programmatically handle :before?

Tags:

css

reactjs

less

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??

like image 892
Hao Avatar asked Sep 27 '14 01:09

Hao


3 Answers

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
}
like image 133
am2505 Avatar answered Oct 27 '22 05:10

am2505


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.

like image 45
Ross Allen Avatar answered Oct 27 '22 03:10

Ross Allen


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.

like image 25
BrunoElo Avatar answered Oct 27 '22 03:10

BrunoElo