DEV Community

Cover image for React: Conditional rendering
DrSimple
DrSimple

Posted on

React: Conditional rendering

This is one of the concepts I found most confusing when I started React. This post is a simple demonstration of how to render components with react using conditional rendering.

Let's get to it

🥦 Create a react project using npx create-react-app .
Image description

🥦 Then start the react app using this command: npm start, this opens up the react page on the default localhost:3000
Image description

Clean Up

Next, we cleanup our src folder and just have a h1 tag inside the App.jsthat says Choose your favorite pet.

import logo from "./logo.svg"; import "./App.css"; function App() { return ( <div className="App"> <h1>Choose your favorite pet</h1>  </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

🥦 Let's give this a well.
Our result:
Image description

🥦 Next, we create a component folder and a file, I call it Choose.jsx. You can call it whatever you like.

  • Create a component
import React from "react"; export const Choose = () => { return ( <div> <p>I am a cute Dog</p>  <img src="https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.countryliving.com%2Flife%2Fkids-pets%2Fnews%2Fa44032%2Fdog-owners-take-more-pictures-of-their-pet-than-their-spouse%2F&psig=AOvVaw1qbUbk4x640915cLFiHmZ0&ust=1642064745637000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCMDU14Duq_UCFQAAAAAdAAAAABAJ" alt="cute dog" /> </div>  ); }; 
Enter fullscreen mode Exit fullscreen mode

🥦 Now let's import our Choose.jsx into the App.js component.

import "./App.css"; import { Choose } from "./components/Choose"; function App() { return ( <div className="App"> <h1>Choose your favorite pet</h1>  <Choose /> </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

You should have the following on save:


🥦 Now let's write the logic that toggles our dog into a cat.
import useState Hook and declare an initial value for your useState.

import { useState } from "react"; import "./App.css"; import { Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false) return ( <div className="App"> <h1>Choose your favorite pet</h1>  <Choose /> </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

🥦 Next, we create a button with an onClick function, and we tell it to change the setToggle state to true

import { useState } from "react"; import "./App.css"; import { Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false); return ( <div className="App"> <button onClick={() => setIsToggle(!toggle)}>Change</button>  <h1>Choose your favorite pet</h1>  <Choose /> </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

🥦 Now, whenever we click our button, the value of our toggle is set to the inverse of its initial value.
Let me show you how this works by adding a console.log to the isToggle variable.

import { useState } from "react"; import "./App.css"; import { Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false); return ( <div className="App"> <button onClick={() => setIsToggle(!toggle)}>Change</button>  {console.log(toggle)} <h1>Choose your favorite pet</h1>  <Choose /> </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

🥦 If you open your developer console by pressing f12 or use the inspect we have:
Image description

Now, using ternary operators, let's build a conditional rendering that says, "Render my lovely dog or give me a cat."

🎯 Method 1: Inline If with Logical && Operator

import { useState } from "react"; import "./App.css"; import { Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false); return ( <div className="App"> <h1>Choose your favorite pet</h1> <button onClick={() => setIsToggle(!toggle)}>Change</button> {toggle && <Choose />} </div> ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

Explanation:

{toggle && <Choose />} this means if toggle is true, render component.

🎯 Method 2: Inline If-Else with Conditional Operator

Let's bring our cat into the picture by declaring that if we can't choose between a dog and a cat, we'll take a cat.

In the Choose.jsx file, quickly develop and export a working component.

export const Cat = () => { return ( <div> <p>I am a cute Cat</p>  <img src="https://th-thumbnailer.cdn-si-edu.com/ZoiTX0zdWNy5LOUC6Yh-qQsDcsE=/fit-in/1072x0/filters:focal(1834x1782:1835x1783)/https://tf-cmsv2-smithsonianmag-media.s3.amazonaws.com/filer/11/2c/112cfb7f-d73f-40d6-afab-7e05be7c7b73/andy_warhol_ch_6.jpg" alt="cute cat" width="500px" height="380x" /> </div>  ); }; 
Enter fullscreen mode Exit fullscreen mode

Now let's import it into our App.js

import { useState } from "react"; import "./App.css"; import { Cat, Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false); return ( <div className="App"> <h1>Choose your favorite pet</h1>  <button onClick={() => setIsToggle(!toggle)}>Change</button>  <Cat /> {toggle && <Choose />} </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

Our final code

import { useState } from "react"; import "./App.css"; import { Cat, Choose } from "./components/Choose"; function App() { const [toggle, setIsToggle] = useState(false); return ( <div className="App"> <h1>Choose your favorite pet</h1>  <button onClick={() => setIsToggle(!toggle)}>Change</button>  {toggle ? <Choose /> : <Cat />} </div>  ); } export default App; 
Enter fullscreen mode Exit fullscreen mode

This is where the magic happens {toggle ? <Choose /> : <Cat />}.

Here, we are saying if toggle is true render which is our dog and if not render cat.

I hope you found this article useful.For reference, you can find the entire code here click. Thanks

Resources

React.

Top comments (0)