Skip to content

Instantly share code, notes, and snippets.

@ayse8888
Forked from dacre-denny/ToggleDivImage.jsx
Created July 14, 2021 14:45
Show Gist options
  • Save ayse8888/a963e48243952b35ef7c6c5e7302279b to your computer and use it in GitHub Desktop.
Save ayse8888/a963e48243952b35ef7c6c5e7302279b 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