React: Conditional rendering
Tags: javascript, webdev, beginners, react
Published: 2022-01-12 10:34:13

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oku9191i840kykk5juxc.PNG)

🥦 Then start the react app using this command: `npm start`, this opens up the react page on the default <mark>localhost:3000</mark>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rpzf2b6hyaan79habrc.PNG)
 

## Clean Up
Next, we cleanup our src folder and just have a h1 tag inside the <kbd>App.js</kbd>that says <kbd>Choose your favorite pet.
```javascript
import logo from "./logo.svg";
import "./App.css";

function App() {
  return (
    <div className="App">
      <h1>Choose your favorite pet</h1>
    </div>
  );
}

export default App;
```

---

🥦 Let's give this a well.
Our result: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onb073a5otg2ctk295ta.PNG)
 
🥦 Next, we create a component folder and a file, I call it <kbd>Choose.jsx</kbd>. You can call it whatever you like.
* Create a component
```javascript
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>
  );
};
```

🥦 Now let's import our <kbd>Choose.jsx</kbd> into the <mark>App.js</mark> component.
```javascript
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;
```
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. 

```Javascript
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;
```

---

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

```javascript
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;

```
🥦 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. 


```javascript
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;
```

🥦 If you open your developer console by pressing f12 or use the inspect we have:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rpnpbuas7ve7kgsdmaxm.PNG)

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 
```javascrvipt
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;
```

Explanation:

` {toggle && <Choose />}` this means if toggle is true, render <Choose /> 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. 

```javascript
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>
  );
};

```

Now let's import it into our App.js
```javascript
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;
```


Our final code
```javascript
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;
```

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

Here, we are saying if toggle is true render <Choose /> 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](https://github.com/drsimplegraffiti/conditional-render-react-tuts). Thanks 

## Resources
[React](https://reactjs.org/docs/conditional-rendering.html).