How to toggle images/icons using React Hooks for beginners by a beginner

Image from Canva.com

While learning React.js I’ve used this component multiple times to develop different kinds of projects. On this occasion, I’m going to show you how to toggle between two images/icons (stars). It’s going to be perceived as if one star in “on” or “active” when clicked and when clicked again is “off” or inactive. This toggle is the first step, for example, on creating a “add to favorites” component.

Creating our new React app

The first thing we want to do is create our new react app:

npx create-react-app toggle-images

This instruction creates a template of a React application with the name of toggle-images.

Note: npx is not a typo. It is a package runner command included within npm .

Now, you need to navigate to the directory of this application and then run yarn:

cd toggle-images
yarn
yarn start

After running the above code, your browser should open to a URL on localhost:3000 looking like this:

Gif from https://opensource.com/article/20/11/reactjs-tutorial

We are going to do some cleanup, we don’t need the logo, the text nor the link so in App.js component please delete line 1 and from line 8 to line 19 and save. You’ll have something like this:

Open App.css and delete lines 5 to 8, 10 to 14, and 27 to 38, you will end up with something like this:

What we just did is a workaround to have a nice plain canvas with a pretty dark gray background color. There is still some work to do before we start working on our Component.

Creating images and Components.js folder

Next, inside src we are going to create two new folders:

The first one called “images” where we are going to save our two star icons. I’ve used these black and white star and yellow star icons from Flaticon, and I’ve downloaded them in SVG format.

The second folder called “Components”, inside create a file “ToggleImages.js”.

Great job! Up to this point, we have everything set up to start the tutorial!

Let’s import our icons and use them!

Inside ToggleImages.js import the two icons from “ images” folder and use them in the return inside an <img> tag like this:

If you go to your browser you won’t see the icons yet, we have to import and use ToggleImages.js component in App.js. See line 2 for import and line 9 to use our component.

If you go to your browser you should see something like this now:

This is progress! So, now we have to resize the icons to the same size. Create a file ToggleImages.css and select the classes from each <img> tag and resize.

To see the results, import ToggleImages.css into ToggleImages.js. You should see something like this on your browser:

Creating our Hook

Back to App.js

In line 1 we import useState Hook from React. It lets us keep local state in a function component.

In line 6, Inside App component, we declare a new state variable by calling the useState Hook. We’re calling our variable active because when the star is clicked for the first time it will show the yellow star (active) and its value will change to be true.

We initialize it to false as the only useState argument, this means that the black and white star icon will be shown as a default. The second returned item is itself a function. It lets us update active so we’ll name it setActive.

Let’s toggle our icons!

Now, we need to trigger a reaction that will change the state using our hook. Remember that our useState is taking false as its only argument. For this we are going to create a handleChangeActive() function that will change the current state of our toggle when the star is clicked and will set it to the opposite Boolean value. I’ll explain it in more details below:

When a star icon is clicked our handleChangeActive() function is triggered, setActive will update active state to the opposite value of previousStar. If previuosStar is true it will return false and if previuosStar is false it will return true.

Next, we are going to pass handleChangeActive() function and the active state as props to ToggleImages.js component (line 17).

Going back to ToggleImages.js we are going to use object destructuring to make working with props easier. We are going to use curly braces inside the function’s parameter and we are going to define active and handleChangeActive (line 6).

We are going to create an onClick handler inside each <img/> tag element (line 16 and line 23), this will allow us to call the handleChangeActive() function and perform an action when the star icon is clicked.

Ternary operator

Breaking down line 11 to line 25. Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. Inside the curly braces we are going to create a ternary operator to evaluate a condition, when to show the black & white or the yellow star icon. If the condition is truthy, in this case active show the show the yellow star icon else represented by a colon ( : )show the black & white star icon.

This is the result!

Summary

How to create a new React app and delete all the necessary elements to leave a blank canvas with only it’s original grey color. We created two folders, one for the component and the other one to store the icons. You saw how to import a component into App.js. You learned that the onClick handler is triggered every time a star icon is clicked, triggering simultaneously the handleChangeActive() function that will update state active every time previousStar changes its value from false to true or vice versa using Ternary Operator . Also, the only argument that our useState Hook takes in a Boolean that initializes our active state as false.

Making React Functional Component tutorials that made transitioning as a Software Engineer easier. Useful Components that you can reference more than once.