Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Created May 29, 2021 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rw3iss/6a81b70ead292a76cd028bcbf418d5ce to your computer and use it in GitHub Desktop.
Save rw3iss/6a81b70ead292a76cd028bcbf418d5ce to your computer and use it in GitHub Desktop.
MobileComponent
import React, { useEffect, useState } from 'react';
import { isMobile } from 'lib/utils/UiUtils';
// Dynamic component which rendered a different child depending on mobile vs. desktop.
// Will re-render upon resize state change.
export default MobileComponent = ({ component: Component, ...props }) => {
const [currIsMobile, setIsMobile] = useState(isMobile());
useEffect(() => {
window.addEventListener('resize', (e) => {
let _isMobile = isMobile();
if (currIsMobile != _isMobile) {
setIsMobile(_isMobile)
}
});
})
if (currIsMobile) {
return <props.mobile {...props} />
} else {
return <props.normal {...props} />
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment