Card Flipping With React

Without giving any real thought, flipping a card seem pretty simple. But like all things when it comes to doing it you may be lost on where to start. If your application uses cards and you need them to flip when a user click on them, then I hope my explanation can help you. For this example I’m going to be using a class component, however you can of course use a functional component and set state with hooks instead.

First thing we need to do is set state of a variable to a boolean value.

Then build out your front and back card. As you can see I declared ‘frontCard’ and ‘backCard’ within render because we don’t want to initially return those variables. Now in order to flip the ‘false’ value that we set in our state to ‘true’, we need an event listener and invoke a callback function. In line 19 and 27 I did just that, I’m using the onClick event listener and the callback function is named ‘handleClickedCard’.

Now we to tell that callback function what to do with the state when a user click on the card. In the function we are saying that whenever the there is a click, the previous state which by default is ‘false’ is going to turn ‘true’ by using the ! (bang) operator.

Finally we need to return something, in this case we are going to use a ternary operator. With ternary operator we need a condition followed by a question mark (?), the expression on the left is only going to execute if the condition is truthy. And the expression on he right is only going to execute if the condition is falsy. Without the bang (!) in the begging of the condition, it’s going to show the back side of the card because by default the state of the clicked is ‘false’.

At the end, it should look like this.

Here’s the code and link to the repository on GitHub. I hope I helped someone out with this explanation!

https://github.com/JoeG21/medium-ex/tree/master/state-props

I’m a Software Engineer who is always learning something new!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store