If you version images like person-1.jpg
person-2.jpg
, this will let you swap an img element for a Timg component, and clicking on the image cycles through previous versions.
Created
March 5, 2019 20:16
-
-
Save tmcw/82946ce935d243baca95fd0477af4901 to your computer and use it in GitHub Desktop.
Image version navigator
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 Timg extends React.Component { | |
state = {maxVersion: 1}; | |
constructor(props) { | |
super(props); | |
this.state.maxVersion = +props.src.match(/(\d+)\.jpg$/)[1]; | |
this.state.version = this.state.maxVersion; | |
} | |
swap = () => { | |
this.setState(({version, maxVersion}) => { | |
version++; | |
if (version === 0 || version > maxVersion) version = 1; | |
return { | |
version | |
}; | |
}); | |
}; | |
render() { | |
const {src} = this.props; | |
const {version} = this.state; | |
return ( | |
<img | |
onClick={this.swap} | |
{...this.props} | |
src={src.replace(/(\d+)\.jpg$/, version) + ".jpg"} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment