Reputation: 779
I am using Contentful and Gatsby for context. In Contentful a user writes a bunch of content where they can see it preview nicely in the editor. The GraphQL data from it returns something like this
<p>Hello World</p>\n<p><strong>Foo Bar </strong>\n999 172 St. NW\nEdmonton, AB</p>\n<p><strong>Sushi</strong>\n2020 87 Ave.\nEdmonton</p>
I would like to format all the \n (the line breaks) so that the previewed content inside my website looks exactly like the preview in this Content Editor Platform. Right now I don't have any line breaks so all my content would be a giant word blob if I did not format my p tags.
What is the best solution to create these line breaks or to convert all \n to br elements so that each time I have a \n a new line is created on my site?
Currently I am using dangerouslySetInnerHTML attribute on a div to render the content from the example given on the Gatsby site. And styling the html element br
does not work.
Upvotes: 1
Views: 5080
Reputation: 484
Here is a sample code based on @Sasha Ko's Answer.
GraphQL
textField {
childMarkdownRemark {
html
}
}
JSX
<div className="multiline-text"
dangerouslySetInnerHTML={{ __html: textField.childMarkdownRemark.html }}></div>
CSS
.multiline-text{
white-space: pre;
}
Upvotes: 1
Reputation: 373
If you use rich text react renderer with the Rich Text field, you can define custom rendering for your text nodes using the following line in options:
const options = {
renderText: text => text.split('\n').flatMap((text, i) => [i > 0 && <br />,
text])
}
This will find and replace \n with
in your text nodes.
Upvotes: 1
Reputation: 112
I had the same issue, and the fix was super easy. Just add white-space: pre;
style to you div with dangerouslySetInnerHTML
. At least this worked for me. Hope this helps
Upvotes: 2