Reputation: 1906
Is it possible to save markup on a JS object to be retrieved later?
Why?
Here lies my problem, if a description is too long, I'd like to be able to break it into separate chunks, perhaps different HTML tags, as opposed to having the entire text in one long chain of words
ie: after looping through object...
<div>{markup.description}</div>
the above would give me all the description data, but I wouldn't able to massage it (break into bold, italic, headings, or spans.) for a better UI.
So the end result that I'm trying to learn here is how to produce something like:
const markup = [
{
name: "<h1>Joe Doe<h1/>",
food: "<p>pizza<p/>",
description: "<h1>super long description<h2><p>bla bla
bla</p>"
}
]
I tried template literals but no dice.
I know I could separate chunks of text by adding more keys in the object, but that feels redundant because it is all a description, besides I still wouldn't be able to apply any styles (add a class) for words that need attention in the middle of the text.
Upvotes: 1
Views: 583
Reputation: 101690
If you're using React and have JSX available, you can store JSX fragments in a variable and then reference them when you render. However, the markup you've written is very malformed. You have closing tags with the slash in the wrong place and you have an h1
matched up with an h2
. JSX markup has to be valid, and each fragment has to be enclosed in a tag that contains the whole fragment.
const markup = [
{
name: <h1>Joe Doe</h1>,
food: <p>pizza</p>,
description: <div><h1>super long description</h1><p>bla bla bla</p></div>
},
{
name: <h1>Janet Doe</h1>,
food: <p>chicken</p>,
description: <div><h1>yet another super long description</h1><p>bla bla bla</p></div>
}
];
const App = () => (
<div>
{ markup.map(r => [r.name, r.food, r.description]) }
</div>
);
Upvotes: 2
Reputation: 5220
I guess you can always make the properties functions.
const markup = [{
name: () => "<h1>Joe Doe<h1/>",
food: () => "<p>pizza<p/>",
description: () => "<h1>super long description<h2><p>bla bla bla</p>"
}]
function renderMarkup(item) {
let markup = ''
Object.entries(item).forEach(([key, value]) => {
markup += value()
});
return markup
}
$('.markup').html(renderMarkup(markup[0]))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="markup"></div>
Upvotes: 2