Last active
March 19, 2019 15:54
-
-
Save dane-stevens/c8b6801e8ff53d1b9515a572ff1b0297 to your computer and use it in GitHub Desktop.
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
class Img extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
width: 0 | |
} | |
this.imgRef = React.createRef() | |
} | |
componentDidMount() { | |
const width = this.imgRef.current.clientWidth | |
this.setState({ | |
width | |
}) | |
} | |
render() { | |
// Destructure props and state | |
const { src, alt, options = {}, ext = 'jpg' } = this.props | |
const { width } = this.state | |
// Create an empty query string | |
let queryString = '' | |
// If width is specified, otherwise use auto-detected width | |
options['w'] = options['w'] || width | |
// Loop through option object and build queryString | |
Object.keys(options).map((option, i) => { | |
return queryString += `${i < 1 ? '?' : '&'}${option}=${options[option]}` | |
}) | |
return( | |
<figure ref={this.imgRef}> | |
{ | |
// If the container width has been set, display the image else null | |
width > 0 ? ( | |
<img | |
src={`https://cdn.tueri.io/${ src }/${ kebabCase(alt) }.${ ext }${ queryString }`} | |
alt={ alt } | |
/> | |
) : null | |
} | |
</figure> | |
) | |
} | |
} | |
export default Img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment