Skip to main content

Command Palette

Search for a command to run...

Conditionals in React? Are they useful?

Published
2 min read
J

I am a tech lover and frontend developer specializing in creating scalable, user-friendly, and modern websites/web.

My goal is to help users have a smooth and seamless experience on the web.

What are conditionals in React? A simple example of this would be: take for example you have a kid or sibling, and you want them to do something (e.g read for exams). You can give them a condition that if they read a book that day, you'll get ice cream for them.

This same logic applies in React. If a condition is met, something should happen. So now we've seen the logic behind conditionals and a real world example; Now, how do we turn this to a React code?

Below is an example of how we can use this in our React code:

So what in the world is all this rubbish I just wrote in the code? Let's break it down.

First, we created our App component function which is required in every React project and called the component called `Item` where we passed in 2 attributes.

Secondly, we added an if statement in our Item component. This condition displays a paragraph tag with the `content` attribute set in our App component if isPacked is true, and displays nothing if it's false.

This is very useful when you want to manipulate data in React, for example, to display something if the user is signed in or not. I hope this helps you understand conditionals in React better and why they are used.

Thanks for reading. I'll see you in the next blog post :)

G

Awesome :)