In React, you can conditionally render components using if-else statements and ternary operators.
You can use an if-else statement to conditionally render components based on certain conditions.
{Data.map((val, index) => {
if (index < 3) {
return <Blog title={val.title} content={val.content} key={index} />;
} else {
return null;
}
})}
The ternary operator provides a shorter syntax for conditional rendering, introduced in ES6.
{Data.map((val, index) => (
index < 3 ? (
<Blog title={val.title} content={val.content} key={index} />
) : (
null
)
))}
Objective: Create a list of blog posts using the .map()
method and conditionally render the components using if-else statements and ternary operators.
Create a Data File:
// Data.js
export const Data = [
{
id: 1,
title: "Learn HTML",
content: "HTML is Hypertext Markup Language."
},
{
id: 2,
title: "Style your HTML",
content: "CSS is used to style HTML."
},
{
id: 3,
title: "Learn JavaScript",
content: "JavaScript is a programming language."
},
{
id: 4,
title: "Learn React",
content: "React is a JavaScript library for building user interfaces."
}
];
Create a Blog Component:
// Blog.jsx
import React from 'react';
const Blog = ({ title, content }) => {
return (
<div className="blogDiv">
<h2 className="title">{title}</h2>
<p className="content" id="content">{content}</p>
</div>
);
};
export default Blog;
Import Data and Use If-Else Statements in App Component:
// App.jsx
import React from 'react';
import { Data } from './Data';
import Blog from './Blog';
const App = () => {
return (
<>
{Data.map((val, index) => {
if (index < 3) {
return <Blog title={val.title} content={val.content} key={val.id} />;
} else {
return null;
}
})}
</>
);
};
export default App;
Use Ternary Operators for Conditional Rendering:
Update your App.jsx
to use ternary operators for conditional rendering.
const App = () => {
return (
<>
{Data.map((val, index) => (
index < 3 ? (
<Blog title={val.title} content={val.content} key={val.id} />
) : (
null
)
))}
</>
);
};
export default App;
This task will help you practice conditional rendering in React using both if-else statements and ternary operators.