Last active
October 15, 2019 08:37
-
-
Save mkrishnan-codes/ee5f687b0734139afb6560414751f5ae to your computer and use it in GitHub Desktop.
Typescript device component - can be used for rendering different react component for different devices based on width
This file contains 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 * as React from 'react' | |
interface Props { | |
children: React.ReactNode; | |
type: 'desktop' | 'mobile' | 'tablet'; | |
} | |
interface State { | |
width: number; | |
} | |
export const tabWidth = 992; | |
export const mobWidth = 767; | |
export default class Device extends React.Component<Props, State> { | |
constructor(props: Props) { | |
super(props) | |
this.state = { | |
width: window.innerWidth | |
} | |
this.onResize = this.onResize.bind(this); | |
} | |
componentWillMount() { | |
window.addEventListener('resize', this.onResize); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.onResize); | |
} | |
onResize() { | |
this.setState({ width: window.innerWidth }); | |
}; | |
getComponent() { | |
return ( | |
<React.Fragment> | |
{this.props.children} | |
</React.Fragment> | |
) | |
} | |
render() { | |
const { width } = this.state; | |
switch (this.props.type) { | |
case 'desktop': { | |
return width > tabWidth && this.getComponent(); | |
} | |
case 'mobile': { | |
return width <= mobWidth && this.getComponent(); | |
} | |
case 'tablet': { | |
return width > mobWidth && width <= tabWidth && this.getComponent(); | |
} | |
default: return null; | |
} | |
} | |
} |
This file contains 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 * as React from 'react'; | |
export interface Props { | |
children?: React.ReactNode; | |
} | |
export default class Card extends React.Component<Props, any> { | |
render() { | |
return ( | |
<React.Fragment> | |
<Device type="desktop"> | |
<div>I will be there only on a desktop</div> | |
</Device> | |
<Device type="tablet"> | |
<div>I will be there only on a tablet</div> | |
</Device> | |
<Device type="mobile"> | |
<div>I will be there only on a mobile</div> | |
</Device> | |
</React.Fragment> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment