responsive.js
import { useMediaQuery } from "react-responsive";
export default {
sm: useMediaQuery({ maxWidth: 768 }),
md: useMediaQuery({ minWidth: 769, maxWidth: 1024 }),
lg: useMediaQuery({ minWidth: 1025 }),
};
When I tried to import it in App.js
import {sm,md,lg} from "../../responsive"
error occurs:
export 'lg' (imported as 'lg') was not found in '../../responsive' (possible exports: default)
What's wrong?
update
I find that there is another error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at resolveDispatcher (react.development.js:1476)
at Object.useContext (react.development.js:1484)
at useDevice (react-responsive.js:57)
at useMediaQuery (react-responsive.js:95)
at Module../src/responsive.js (responsive.js:3)
After I change to below
import { useMediaQuery } from "react-responsive";
const sm = useMediaQuery({ maxWidth: 768 });
const md = useMediaQuery({ minWidth: 769, maxWidth: 1024 });
const lg = useMediaQuery({ minWidth: 1025 });
export { sm, md, lg };
You can either use a
default
export or anamed
export.Using the
default
export, which is what you have in your question.Alternatively you could use a
named
export.And
import
them via:The issue you're encountering about using a hook outside of a React component is because you are using
useMediaQuery
(a hook) outside of a component, it can be easily remedied by creating a custom, reusable hook.Inside of your component you can use it like so: