Search code examples
javascriptcssreactjspseudo-element

CSS pseudo elements in React


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?


Solution

  • 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.