Mark As Completed Discussion

Conditional Rendering

In React, conditional rendering allows you to show or hide elements based on certain conditions. This is useful for displaying dynamic content or handling user interactions.

Using State to Conditionally Render

To conditionally render elements in React, you can make use of the state. The state represents the current state of your component and can be updated using the useState hook.

Here's an example of conditional rendering using state:

JAVASCRIPT
1import React, { useState } from 'react';
2
3const App = () => {
4  const [show, setShow] = useState(true);
5
6  const handleToggle = () => {
7    setShow(!show);
8  };
9
10  return (
11    <div>
12      <h1>Conditional Rendering</h1>
13      <button onClick={handleToggle}>Toggle</button>
14      {show ? <p>Element is visible</p> : null}
15    </div>
16  );
17};
18
19export default App;

In this example, we start with the initial state of show as true. We have a button that calls the handleToggle function when clicked. This function updates the show state by negating its current value.

Based on the show state, we conditionally render the <p> element. If show is true, the element is visible, otherwise, it is not rendered.

Conditional rendering provides a way to create dynamic and interactive user interfaces in React. It allows you to control the flow of your application based on certain conditions and user interactions.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment