#100DaysOfCode: Day 4

Shawn McMahon
3 min readJul 16, 2021

Day 4 of #100DaysOfCoding. Today I continue my React journey. This week we learned about conditional rendering and prop types.

Source: https://www.pexels.com/photo/body-of-water-during-sunset-1048273/

Conditional Rendering

Conditional rendering is used when you want to display data to the user but only when a certain condition is met.

This snippet of JSX is conditional rendering. On the left side of the && operator, we have the condition that needs to return a true boolean. If the condition returns a true boolean, it will render the JSX tag on the right side of the && operator.

In this case, we are looking at the state object within our component. Inside the state object, we have an error property that contains a string if an error has occurred within the state of the app. The ‘!!’ double bang operator indicates we want to check the error property to see if it is true or if it contains anything at all. If this is the case, we want to return an h2 tag with the interpolated error message on the DOM for the user to read the error.

The ‘&&’ operator is a little different from what I am used to seeing. In most cases, a ‘&&’ operator indicates we want both conditions on the left side and the right side of the operator to return true. However, in this case, we are only looking to evaluate the left side of the operator. Something to keep in mind as I continue applying conditional rendering in my own applications.

Prop Types

As applications grow, it can be easy to acquire a lot of bugs. Our application can crash if we are passing in the wrong data types through our props. To remedy this, prop types come in handy. Prop types is a library, so we always need to remember to import this library at the top of the file!

We can check out if our props are any type of data. We can even check if the prop being passed is a function.

Here is an example of the implementation of prop types in the current project I am working on. In our MoviePage component, we are passing down props from our App component into our single Movie component. The single Movie component needs these specific props so a user can view the details when they click a movie poster. You can notice we also passed down the goBack function we need in order to return to the home screen, so it’s not just checking for primitive data types.

That’s enough for today. See you tomorrow!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shawn McMahon
Shawn McMahon

Written by Shawn McMahon

Software Engineer, Snowboarder, Music Enthusiast

No responses yet

Write a response