I am trying to map through an object that is passed as prop and want to display different HTML elements for different object values
Object;
const allDesc = {description: "Title Description", description1: "Intro
Description", description3:"Sub title", description3: "Sub Description"}
Code:
<div>
{Object.keys(allDesc).map((desc, index) => {
if (allDes[desc] !== "") {
return (
<>
<h1>allDesc.description</h1>
<p>allDesc.description1</p>
<h3>allDesc.description2</h3>
<p>allDesc.description3</p>
</>
);
}
})}
</div>
This approach displays nothing, what would be the correct approach for mapping through an object and displaying different HTML elements for different object values. Thanks!
Please try this.
<div>
{Object.keys(allDesc).map((desc, index) => {
if (allDes[desc] !== "") {
return (
<>
{
desc === 'description' ? <h1>allDes[desc]</h1> :
<p>allDes[desc]</p>
}
</>
);
}
})}
</div>
this allDes[desc] is have the value of all field you loop from the Object keys.
map over the Object.entries. If the key matches "description" return the value as an <h1>, otherwise return the value as a <p>.
function Example({ allDesc }) {
return (
<div>
{Object.entries(allDesc).map(([key, value]) => {
if (key === 'description') return <h1>{value}</h1>;
if (key === 'description3') return <h3>{value}</h3>;
return <p>{value}</p>;
})}
</div>
);
};
const allDesc = {description: 'Title Description', description1: 'Intro Description', description3: 'Another Description', description4: 'More text' };
ReactDOM.render(
<Example allDesc={allDesc} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>