Using <style /> blocks in React

Every once in a while you are faced with a scenario where the best course of
action is to slap a <style /> block in the middle of your code.

For us, it was that time we wanted to set an arbitrary width (selected by the
user) on a component, based on device’s screen size.

If it had not been contingent on the screen size, it would have been NBD and we
could have set the style property right on the component. Since we needed to
use a media query, we were forced to use a <style /> block.

Unfortunately, using <style /> blocks in React is easier said than done as the
CSS syntax includes fancy braces that are reserved as part of the JSX syntax.

Never fear though, you can just treat the CSS syntax as a string or template
literal and you are good to go:

const height = 200

return (
  <React.Fragment>
    <style>
      {`
        @media (min-width: 768px) {
          .awesome-div {
            height: ${height}}
      {'
        .inner-div {
          border: 1px solid red;
        }
      '}
    </style>
    <div className="awesome-div">
      <div className="inner-div">
        Awesome sauce!
      </div>
    </div>
  </React.Fragment>

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.