Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  143] [ 2]  / answers: 1 / hits: 30848  / 6 Years ago, mon, july 23, 2018, 12:00:00

So for example this is my view:



<div>
<img src='../../minus.png' />
</div>


Now I want to make that on each click the image changes from plus.png to minus.png.



So, click once: minus.png => plus.png, click again: plus.png => minus.png, and so on. How can I make this?


More From » html

 Answers
43

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


[#53909] Thursday, July 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;