When using JSON data from the backend to display text in HTML of your web application, we often encounter a problem where we need to change the paragraph or add a bullet point. To achieve the same, we sometimes settle by creating different object properties in the JSON for different paragraphs and bullets points. We display the same by using <br/>
tag separated spans or paragraphs. This increases the complexity of the code and we end up with a messy code.
<!DOCTYPE html>
<html>
<body>
<h2>JSON without line break</h2>
<span id="para1"></span><br/>
<span id="para2"></span>
<script>
const withoutLineBreak = {
paragraph1: "Lorsem Ipsum",
paragraph2: "Lorsem Ipsum"
}
document.getElementById("para1").innerHTML =
withoutLineBreak.paragraph1;
document.getElementById("para2").innerHTML =
withoutLineBreak.paragraph2;
</script>
</body>
</html>
As we can’t add <br/>
tag in JSON, we need to use \n
(newline) before the start of the next paragraph or bullet point to break the line in JSON. You can now use a single object property for multiple paragraphs and bullet points. This significantly reduces the line of code in the HTML file.
<!DOCTYPE html>
<html>
<body>
<h2>JSON with line break</h2>
<span id="para" style="white-space:pre"></span>
<script>
const withLineBreak = {paragraph: "Lorsem Ipsum\nLorsem Ipsum"}
document.getElementById("para").innerHTML = withLineBreak.paragraph;
</script>
</body>
</html>
Even after adding \n
to the string, you still see that the JSON is not breaking into separate paragraphs. This is because the CSS property white-space is set to normal by default.
In order to break the line, one needs to add the following style to paragraph or span.
white-space: pre;
pre stands for preformatted text. It will preserve the white space and text will only wrap on line breaks.
Use case: When developing a FAQ page for your web application and the data is coming in form of JSON from the backend.
Follow us on Instagram
Top comments (0)