Created
July 23, 2019 10:56
-
-
Save dacre-denny/676fe01ab4d8f8fa764d52201e9f967c to your computer and use it in GitHub Desktop.
Toggle image with react and hooks
This file contains hidden or 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