How to perform conditional rendering in React.js



Image not found!!

Conditional rendering in React.js allows you to show or hide components based on certain conditions. There are several ways to perform conditional rendering in React, and the approach you choose depends on the specific requirements of your application. Here are some common methods:

1. Using if statements:

jsx
import React from 'react'; const MyComponent = ({ condition }) => { if (condition) { return <p>This content is rendered conditionally.</p>; } else { return <p>This content is not rendered conditionally.</p>; } }; export default MyComponent;

2. Using the ternary operator:

jsx
import React from 'react'; const MyComponent = ({ condition }) => { return ( <div> {condition ? <p>Rendered if condition is true</p> : <p>Rendered if condition is false</p>} </div> ); }; export default MyComponent;

3. Using logical && operator:

jsx
import React from 'react'; const MyComponent = ({ condition }) => { return ( <div> {condition && <p>Rendered if condition is true</p>} </div> ); }; export default MyComponent;

4. Using a function for rendering logic:

jsx
import React from 'react'; const MyComponent = ({ condition }) => { const renderContent = () => { if (condition) { return <p>Rendered if condition is true</p>; } else { return <p>Rendered if condition is false</p>; } }; return <div>{renderContent()}</div>; }; export default MyComponent;

5. Using map for rendering a list conditionally:

jsx
import React from 'react'; const MyComponent = ({ items }) => { return ( <ul> {items.map(item => ( item.condition && <li key={item.id}>{item.text}</li> ))} </ul> ); }; export default MyComponent;

6. Using Switch Statements:

jsx
import React from 'react'; const MyComponent = ({ condition }) => { switch (condition) { case 'case1': return <p>Rendered for case 1</p>; case 'case2': return <p>Rendered for case 2</p>; default: return <p>Rendered for default case</p>; } }; export default MyComponent;

Choose the method that fits your use case best. Keep in mind that the specific method you use may depend on the complexity of your conditions and the structure of your components.