Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data from react component to css file [duplicate]

I'm building React components. I have added CSS inline in the components as suggested in this brilliant presentation by one of the people behind React. I've been trying all night to find a way to add CSS pseudo classes inline, like on the slide titled "::after" in the presentation. Unfortunately, I do not just need to add the content:""; property, but also position:absolute; -webkit-filter: blur(10px) saturate(2);. The slides show how to add content through {/* … */}, but how would you add other properties?

like image 601
Michael Johansen Avatar asked Nov 29 '25 14:11

Michael Johansen


2 Answers

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

like image 91
Michael Johansen Avatar answered Dec 02 '25 04:12

Michael Johansen


Inline styles cannot be used to target pseudo-classes or pseudo-elements. You need to use a stylesheet.

If you want to generate CSS dynamically, then the easiest way is to create a DOM element <style>.

<style
  dangerouslySetInnerHTML={{
    __html: `
      .my-special-div:after {
        content: "Hello";
        position: absolute
      }
    `
  }}
></style>
<div className="my-special-div"></div>
like image 39
Wiktor Kozlik Avatar answered Dec 02 '25 03:12

Wiktor Kozlik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!