Using <style /> blocks in React

Josh Sherman
1 min read
Software Development CSS

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}px;
          }
        }
      `}
      {'
        .inner-div {
          border: 1px solid red;
        }
      '}
    </style>
    <div className="awesome-div">
      <div className="inner-div">
        Awesome sauce!
      </div>
    </div>
  </React.Fragment>
);
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles