-
-
Save ayse8888/a963e48243952b35ef7c6c5e7302279b to your computer and use it in GitHub Desktop.
Toggle image with react and hooks
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
/* Functional component based on hooks that toggles image when button clicked */ | |
const ToggleDivImage = () => { | |
/* Setup component state that tracks visibility of the image. Initially, we'll set | |
the image to visible (toggled true) */ | |
const [toggled, setToggled] = React.useState(true); | |
/* Define a function that toggles the visibility of the image */ | |
const toggleImage = () => setToggled(!toggled); | |
return ( | |
<div> | |
{/*Render toggle button, and bind toggleImage to click handler */} | |
<button onClick={toggleImage}>Toggle Image</button> | |
{/* Render image if toggled is truthy */} | |
{toggled && <img src="http://www.funnycatsite.com/pictures/Jumping_For_Big_Joy.jpg" alt="Cat" />} | |
</div> | |
); | |
}; | |
/* Usage | |
<ToggleDivImage /> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment