0

I need to create a CSS class with media queries based on input image. The react script to create the css should look something like this:

  const getBackgroungImageSet = (image) => {
    return `.mycontainer {    
                background-image:url("${image}?mw=500"); // big image   
            }
            
            @media(max-width: 768px){
              .mycontainer {
                    background-image:url("${image}?mw=250"); // small image  
                }
            }`;
  }

Is it possible to add this class to the document in react?

1 Answer 1

1

Here's a way to add your styles via a style tag. The actual method is based on something shown in the docs for React Helmet. Which is a good way of getting your style tags to the document head instead of arbitrarily in the middle of the dom.

For the style tag, you need to use type="text/css" and use a string so that there aren't syntax errors due to CSS syntax not being valid in JSX.

function Example() {
  return (
    <div>
      <span>This should be purple</span>
      <br/>
      <span>This should have a blue border</span>
      <style type="text/css">{`
        span {
          color: purple;
        }
        span:nth-of-type(2){
          color: inherit;
          border: 2px solid blue;
        }
      `}</style>
    </div>
  );
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.