Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 6

Conditional Rendering in REACT

Using Ternary Operators

A few basic examples:

Conditional rendering in JSX allows you to conditionally include or exclude elements or


components based on a certain condition. This is a fundamental concept in React that allows you to
create dynamic user interfaces based on the state or props of your components.

Here are a few simple examples of conditional rendering in JSX:

1. **Using Ternary Operator:**

```jsx
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;

return (
<div>
{isLoggedIn ? (
<h1>Welcome, User!</h1>
):(
<button>Login</button>
)}
</div>
);
}
```

In this example, if `isLoggedIn` is true, it renders a welcome message. Otherwise, it renders a login
button.

2. **Using Logical AND Operator:**

```jsx
function ShowMessage(props) {
const showMessage = props.showMessage;

return (
<div>
{showMessage && <p>This is a message.</p>}
</div>
);
}
```

Here, if `showMessage` is true, it renders the message. If `showMessage` is false, nothing is


rendered.

3. **Using a Function:**
```jsx
function UserGreeting() {
return <h1>Welcome back, User!</h1>;
}

function GuestGreeting() {
return <h1>Please sign up.</h1>;
}

function Greeting(props) {
const isLoggedIn = props.isLoggedIn;

if (isLoggedIn) {
return <UserGreeting />;
} else {
return <GuestGreeting />;
}
}
```

In this example, the `Greeting` component renders either the `UserGreeting` or `GuestGreeting`
component based on the `isLoggedIn` prop.

4. **Conditional Rendering with State:**

```jsx
function ToggleButton() {
const [isOn, setIsOn] = useState(false);

const handleClick = () => {


setIsOn(!isOn);
};

return (
<div>
{isOn ? (
<button onClick={handleClick}>Turn Off</button>
):(
<button onClick={handleClick}>Turn On</button>
)}
</div>
);
}
```

Here, clicking the button toggles the state between `isOn` and `!isOn`, which determines whether to
render "Turn On" or "Turn Off" button.

These are basic examples to illustrate the concept of conditional rendering in JSX. In more complex
applications, you can use conditional rendering to control the display of components, sections, or
entire views based on various conditions and user interactions.
A more detailed example using a Clothing Store App that includes a
1. Product Page,
2. Contact Page,
3. Header Component with a Notification Message, that receives output from a;
4. Basic Login function and a;
5. Basic Logout function, linked to a;
6. Button.

```jsx
import React, { useState } from 'react';
import Container from 'react-bootstrap/esm/Container';
import Navbar from 'react-bootstrap/Navbar';
import Button from 'react-bootstrap/Button';
import { Routes, Route, Link } from 'react-router-dom';
import logo from "./crockett-and-bond-red-gold.png";
import image from "./jb-cj-collection.jpg"

// Component to display a welcome message


function Welcome(props) {
return (
<Container className='text-center' style={{ border: '2px solid white', color: 'gold',
backgroundColor: 'darkBlue', opacity: '0.75' }}>
<h4>Welcome {props.name}!</h4>
</Container>
);
}

// Component for sign-up button


function SignIn({ onSignIn }) {
return <Button type="button" onClick={onSignIn}>Agent Sign In</Button>;
}

// Component for sign-out button


function SignOut({ onSignOut }) {
return <Button type="button" onClick={onSignOut}>Agent Sign Out</Button>;
}

// Component to greet the user based on login status


function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
const userName = props.name;

// Conditional rendering using the ternary operator


return (
<div>
{isLoggedIn ? (
// User is logged in
<div>
<Welcome name={userName} />
<Container className='text-center' style={{ border: '2px solid white', color: 'gold',
backgroundColor: 'darkBlue', opacity: '0.75' }}>
{/* Rendering the SignOut component with onSignOut prop */}
<SignOut onSignOut={props.onSignOut} />
</Container>
</div>
):(
// User is not logged in
<div>
<Container className='text-center' style={{ border: '2px solid white', color: 'gold',
backgroundColor: 'darkBlue', opacity: '0.75' }}>
{/* Rendering the SignIn component with onSignIn prop */}
<SignIn onSignIn={props.onSignIn} />
</Container>
</div>
)}
</div>
);
}

// Component for the landing page


function Landing() {
return (
<Container className='text-center' style={{ border: '2px solid white', color: 'white',
backgroundColor: 'black', opacity: '0.90' }}>
<div>
<main>
<img src={image} alt='' />
<p>Founded in 1853, Crockett & Bond Rewards The Connoisseur with the World's Finest in
Hand-Stitched, Expertly-Crafted Shoes</p>
</main>
<nav>
<Link to="/cart">Contact</Link>
</nav>
</div>
</Container>
);
}

// ... (Similar components for ShoppingCart and Product)

// Component for the header


function Header(props) {
const isLoggedIn = props.isLoggedIn;

return (
<Navbar className="bg-body-tertiary">
<Container className='text-center' style={{ border: '2px solid white', backgroundColor: 'white'
}}>
<Navbar.Brand href="#home">
<img
alt=""
src={logo}
width="50"
height="50"
className="d-inline-block align-center"
/>{' '}
Crockett & Bond
</Navbar.Brand>
{/* Display login status using ternary operator */}
<p>You are {isLoggedIn ? 'logged in' : 'not logged in'}</p>
</Container>
</Navbar>
);
}

// Main App component


function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);

const products = [
// ... (Product data)
];

return (
<div className="App">
{/* Render the Header component with isLoggedIn prop */}
<Header isLoggedIn={isLoggedIn} />
{/* Render the Greeting component */}
<Greeting
isLoggedIn={isLoggedIn}
name="Agent"
onSignIn={() => setIsLoggedIn(true)}
onSignOut={() => setIsLoggedIn(false)}
/>
{/* Define routes using React Router */}
<Routes>
<Route exact path="/" element={<Landing />} />
{/* ... (Other routes) */}
</Routes>
{/* Render Product components */}
{products.map(product => (
<Product key={product.id} name={product.name} price={product.price}
image={product.image} />
))}
</div>
);
}

export default App;


```

**Explanation:**
1. **Ternary Operator in `Greeting` Component:**

The `Greeting` component uses a ternary operator to conditionally render content based on
whether the user is logged in or not. The ternary operator has two parts separated by a `?` symbol.
The first part is the condition (`isLoggedIn`), followed by a `:` symbol, and then the two possible
outcomes for the true and false cases.

- If `isLoggedIn` is `true`, it renders the content for a logged-in user (including the `Welcome`
component and `SignOut` button).
- If `isLoggedIn` is `false`, it renders the content for a user who is not logged in (including the
`SignIn` button).

2. **Usage of Components and Props:**

- `Welcome`, `SignIn`, and `SignOut` components are functional components that take props and
return JSX elements with specific styles and behavior.
- The `Greeting` component receives props like `isLoggedIn`, `name`, `onSignIn`, and
`onSignOut`, and it dynamically renders either the logged-in or not logged-in content.

3. **Ternary Operator in `Header` Component:**

- The `Header` component uses a ternary operator to display a message based on the `isLoggedIn`
prop. If the user is logged in (`isLoggedIn` is `true`), it displays "You are logged in"; otherwise, it
displays "You are not logged in".

4. **State and Functions in `App` Component:**

- The `App` component manages the `isLoggedIn` state using the `useState` hook. It also defines
an array of product data.
- It passes the `isLoggedIn` state and functions (`onSignIn` and `onSignOut`) as props to child
components like `Header` and `Greeting`.

5. **React Router (`Routes`, `Route`, `Link`):**

- The `Routes` component from `react-router-dom` is used to define routes for different pages in
the application.
- `Route` components define the paths and corresponding components to be rendered for those
paths.
- `Link` components are used to create navigation links between different routes.

The provided code creates a simple React application with conditional rendering based on the user's
login status. It also demonstrates how to use the ternary operator to conditionally render content and
how to link child components and functions through props.

You might also like