CodeX
Published in

CodeX

“If I created it, only I can move the bricks.” Conditional Rendering in React

Image from the Lego Ideas Web Site.

This article is a continuation of my JSON Web Token Authentication on React article. In case you need to know how to implement JWT tokens to your React/Redux app. Feel free to read it.

Once our users sign up and sign in to our app, we have to set some rules, which users will have authorizations to create, update and delete all they want, when they want and however they want. We don’t want chaos in our app.

We don’t want our app to look like a mess of Lego pieces.

That’s where the conditional rendering comes to play. In my last authentication-related article, I provided one conditional rendering I coded to let the users know if they need to log in or else they can log out.

Will make the navbar change to the following:

My React/Redux app is for sharing and listening to podcasts. So I need the correct authorization for the users that will log in. Only the creator will edit and add episodes to their podcasts. To figure out how we code the conditional statement, let’s go back to the route in the App.js file.

The Route

We’re using routerProps to pass the props to the Podcast component. We find the requested podcast to see in /podcasts/:id by declaring podcast as a variable and using the .find method to equal to routerProps.match.params.id. If the requested id exists, it will render the Podcast component with the requested podcast’s data. If the id doesn’t exist, the path will render the Error component.

return (!!podcast) ? ( <Podcast {...routerProps} {...podcast}/> ) : ( < Error />)

See how we use conditional statements since we send a request to show a specific podcast. If you need more information regarding how router props work, I suggest checking the react-router documentation.

The Component

As you can see above, that’s the entire Podcast component. A good decision I made was creating functional components. After all, my main goal was to render the podcast pages. Not only it’s easier to code, but you can also use hooks and, I love using them.

First, we are iterating the podcast using return (remember, there’s no render in functional components). We are displaying the podcast title, the image, and the website. Additionally, we need to have the episodes on the Podcast page. To make sure we’re rendering the correct podcast episodes, we need to tell the app to display those specific episodes if that podcast has any episodes created. That’s where conditional rendering comes into play. Here, we’ll make sure history.location.pathname is the same as the podcast/:id route.

{(!!history && history.location.pathname === `/podcasts/${id}`) ? <EpisodesContainer podcast={{id, title, image_format, website, user_id, episodes}}  currentUser={user} /> : null}        

As you can observe, we are calling the entire EpisodesContainer. Since this is a small app with only two episodes components, I decided to have both the EpisodeInput and Episodes components as I wanted the user to see both. In the line of code, we have to call EpisodeContainer we pass the podcast props. We’re using the props to see the correct episodes we want to listen to and also be able to add other episodes to that same podcast.

The Container

Above is the code from the entire EpisodesContainer file and this is a class component I haven’t changed to a functional one. I decided to leave all my class components for two reasons, I can go over class components in my project, and I’d also like to leave the bare bones as they were when I was still a Bootcamp student.

To accomplish having just the podcast creator add its episodes and make the changes, we’re going back to the Podcast component and adding the useSelector hook.

import { useSelector } from ‘react-redux’const user = useSelector(state => state.authorization.currentUser)

Now that we’re importing the useSelector hook from react-redux, let’s pass the currentUser state by creating a variable that we’ll call user.

<EpisodesContainer podcast={{id, title, image_format, website, user_id, episodes}} currentUser={user} />

That’s the user variable that’s passed as currentUser when we call the episode container, thanks to the redux state.

{(parseInt(this.props.podcast.user_id) === parseInt(this.props.currentUser?.data?.id)) ? < EpisodeInput podcast={this.props.podcast} /> : null}

Going back to the episode container, it’s time to finally code the conditional rendering that will podcasts creators will love. We’ll make sure that this.props.podcast.user_id and this.props.currentUser.data.id are the same. As parseInt() is used, the Ids we’re comparing pass as integers.

If you’re using Redux as the state manager, always remember to check the data tree and make sure to call the props you passed and what you want to compare. In this case, I wanted to check if the podcast’s user_id is the same as the currentUser. In the Redux tree, this user id is inside data.

Graphic from this highly recommended article on freeCodeCamp.

So there we have it, we finally got things in order, and everything is awesome. Your app can be as organized as the most rigorous lego sets with some responsible users creating and posting the content. I hope this helps you implement conditional rendering in your own React project or understand it a bit better. Happy coding!

The Lego Movie, property of Warner Bros.

Summary

  1. Introduction to Conditional Rendering
  2. React Router
  3. React Components, UI Rendering
  4. userSelector Hook
  5. React Container
  6. Redux State Tree

References

  1. React Router Documentation
  2. React Redux Documentation
  3. MDN Web Docs, parseInt
  4. The Best Way to Architect Your Redux App, Das Lusan, freeCodeCamp

--

--

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