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

Bill
  • 17,872
  • 19
  • 83
  • 131

2 Answers2

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;
0

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

Bill
  • 17,872
  • 19
  • 83
  • 131