Skip to content

Instantly share code, notes, and snippets.

@dacre-denny
Created July 23, 2019 10:56
Show Gist options
  • Save dacre-denny/676fe01ab4d8f8fa764d52201e9f967c to your computer and use it in GitHub Desktop.
Save dacre-denny/676fe01ab4d8f8fa764d52201e9f967c to your computer and use it in GitHub Desktop.
Toggle image with react and hooks
/* 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