Bill
Bill

Reputation: 19248

Mediaquery with Reactjs inline CSS

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

Upvotes: 0

Views: 1120

Answers (2)

Mahbub Hasan
Mahbub Hasan

Reputation: 121

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;

Upvotes: 1

Bill
Bill

Reputation: 19248

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

Upvotes: 0

Related Questions