Skip to content

Instantly share code, notes, and snippets.

@tmcw tmcw/README.md
Created Mar 5, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.