Last active
December 2, 2019 19:22
-
-
Save mistercoffee66/e912e141af4c615ffde87337ef72ad44 to your computer and use it in GitHub Desktop.
example of using React context hook for responsive design
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useState } from 'react'; | |
import PropTypes from 'prop-types'; | |
const mq = 'screen and (max-width: 671px)'; | |
const ResponsiveContext = createContext(); | |
const ResponsiveContextProvider = ({ children }) => { | |
const [isMobile, setIsMobile] = useState(window.matchMedia(mq).matches); | |
matchMedia(mq).addEventListener('change', e => setIsMobile(e.matches)); | |
return <ResponsiveContext.Provider value={{ isMobile }}>{children}</ResponsiveContext.Provider>; | |
}; | |
ResponsiveContextProvider.propTypes = { | |
children: PropTypes.node.isRequired | |
}; | |
export { ResponsiveContext, ResponsiveContextProvider }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { ResponsiveContextProvider } from './ResponsiveContext'; | |
import MyComponent from './MyComponent'; | |
const app = () => ( | |
<ResponsiveContextProvider> | |
<MyComponent /> | |
</ResponsiveContextProvider> | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext } from 'react'; | |
import { ResponsiveContext } from './ResponsiveContext'; | |
const MyComponent = () => { | |
const { isMobile } = useContext(ResponsiveContext); | |
return isMobile | |
? ( <h1>I'm mobile</h1> ) | |
: ( <h1>I'm desktop</h1> ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment