Change image on click - React
This can be achieved with a simple toggle handler:
const imagesPath = {
minus: "https://images.vexels.com/media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png",
plus: "https://cdn3.iconfinder.com/data/icons/glypho-generic-icons/64/plus-big-512.png"
}
class App extends React.Component {
state = {
open: true
}
toggleImage = () => {
this.setState(state => ({ open: !state.open }))
}
getImageName = () => this.state.open ? 'plus' : 'minus'
render() {
const imageName = this.getImageName();
return (
<div>
<img style={{maxWidth: '50px'}} src={imagesPath[imageName]} onClick={this.toggleImage} />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Edit
Note that I passed a function parameter for setState
because my new state depends on the old state. You can read more about it in the docs