How to preserve newlines from Sanity text fields in HTML/React?
You're dealing with a common issue where plain text fields preserve newlines as \n characters, but HTML/React renders them as spaces. Here are your options:
Quick CSS Solution
The simplest approach is to use CSS white-space property:
<div style={{ whiteSpace: 'pre-wrap' }}>
{yourTextField}
</div>Or with a CSS class:
.preserve-newlines {
white-space: pre-wrap;
}This tells the browser to honor newline characters while still wrapping long lines normally.
JavaScript Solution
If you need more control, you can split on newlines and insert <br> tags:
{yourTextField.split('\n').map((line, i) => (
<React.Fragment key={i}>
{line}
{i < yourTextField.split('\n').length - 1 && <br />}
</React.Fragment>
))}Better Long-term Solution: Use Portable Text
If you need any formatting beyond simple line breaks (bold, italic, links, etc.), consider using Sanity's Portable Text/block content field type instead of a plain text field. It's designed for this exact use case and gives you:
- Proper paragraph and line break handling out of the box
- Rich text formatting capabilities
- Structured, portable content that renders consistently
Change your schema from:
{
name: 'myField',
type: 'text'
}To:
{
name: 'myField',
type: 'array',
of: [{type: 'block'}]
}Then render it with a Portable Text component for your framework (React, Vue, Svelte, etc.).
But if you're sticking with plain text fields and just need newlines preserved, the white-space: pre-wrap CSS solution is your best bet!
Show original thread17 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.