Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created March 5, 2019 20:16
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 tmcw/82946ce935d243baca95fd0477af4901 to your computer and use it in GitHub Desktop.
Save tmcw/82946ce935d243baca95fd0477af4901 to your computer and use it in GitHub Desktop.
Image version navigator

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.

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