0

Wondering if there is a way to do @media query within react component. I think having inline style make a lot sense doing components.

i know there is a solution with http://projects.formidablelabs.com/radium/. but is there a way to archive without the lib.

Thanks for any great suggestions

2
  • 1
    use window.matchMedia()? Commented Oct 28, 2015 at 4:22
  • @LiYinKong thanks mate one nice choice (IE 9 not support, which is pain) Commented Oct 28, 2015 at 4:45

2 Answers 2

1

I found this answer in this link. I have no credit. link: https://stackoverflow.com/a/68606754/14765047

import React, { useState, useEffect } from 'react';

const App = () => {
  const [matches, setMatches] = useState(
    window.matchMedia("(min-width: 768px)").matches
  )

  useEffect(() => {
    window
    .matchMedia("(min-width: 768px)")
    .addEventListener('change', e => setMatches( e.matches ));
  }, []);

  return (
    <div >
      {matches && (<h1>Big Screen</h1>)}
      {!matches && (<h3>Small Screen</h3>)}
    </div>
  );
}

export default App;
Sign up to request clarification or add additional context in comments.

Comments

0

i found this answer myself: https://github.com/gajus/react-css-modules combine with webpack css-loader can be very nice :)

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.