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:
jsximport 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;
jsximport 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;
jsximport React from 'react';
const MyComponent = ({ condition }) => {
return (
<div>
{condition && <p>Rendered if condition is true</p>}
</div>
);
};
export default MyComponent;
jsximport 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;
map
for rendering a list conditionally:jsximport React from 'react';
const MyComponent = ({ items }) => {
return (
<ul>
{items.map(item => (
item.condition && <li key={item.id}>{item.text}</li>
))}
</ul>
);
};
export default MyComponent;
jsximport 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.