I'm working on solving a blog post issue: formatting posts to reflect newlines/paragraphs.
Currently, when you create a blog post, you're directed to a <textarea>
in which you can enter the body of the blog post. Submitting the form creates a POST request that inserts the text data (and related information) into the database.
The problem lies in formatting of new lines. When you hit enter inside of the <textarea>
, the cursor drops to the next line, where you can resume writing. But when you view the submitted post, the new lines are rendered as spaces.
Here's an example. Text is submitted formatted like so:
Some sample text.
This is line two.
Each line of text is separated from the others by an empty line.
Once saved and displayed on the page, the above entry appears like this:
Some sample text. This is line two. Each line of text is separated from the others by an empty line.
My goal is to render those new lines to accurately reflect the intent of the writer.
Investigate
The first step is to see what's happening with the text. How is it stored in the DB and how is it reproduced on the site in on the Post page?
Looking up the post in the Mongo client, I can view the text as it's stored in the database:
{
...
text: Some sample text./nThis is line two./nEach line of text is separated from the others by an empty line.'
...
}
So hitting 'enter' to create new lines is saved a /n
somewhere along the way between hitting 'submit' and being stored as data.
And then those newlines (/n
) are not rendered on the page as new lines, instead, they render as spaces.
How are chunks of text properly demarked/delimited/formatted in html? Well <p>
elements seem like the way to go.
To make sure, I'll check out how other blogging sides do it. If a site like dev.to does it that way, I'll consider it a satisfactory implementation.
Newlines into Paragraphs
Inspecting my own dev.to post in Chrome's developer tools, I notice that all of their paragraphs are wrapped in <p>
elements. Hypothesis confirmed. That's what I'll do too.
And this is what it looks like:
<div id='create_container__main__post_text'>
{post.text.split('\n').map(para => (
<p>{para}</p>
))}
</div>
Top comments (0)