Skip to content

Instantly share code, notes, and snippets.

@willhackett
Created April 17, 2018 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willhackett/210a9441d12b54f2f4ae6d62300c79aa to your computer and use it in GitHub Desktop.
Save willhackett/210a9441d12b54f2f4ae6d62300c79aa to your computer and use it in GitHub Desktop.
Line breaks & Paragraphs in React
import React, { Fragment } from 'react'
type PropsType = {
children: string, // yes, the child may only be a string - deal with it.
}
const Text = ({ children }: PropsType) => (
<Fragment>
{children.split('\n\n')
.filter(x => x !== '')
.map((par, i) => {
const paragraph = par.split('\n').filter(x => x !== '')
return (
<p>
{
paragraph.map((line, ii) => (
<Fragment key={ii}>{line}{(ii < paragraph.length - 1) && <br />}</Fragment>
))
}
</p>
)
})}
</Fragment>
)
export default Text
/*
Use like this:
const someText = 'your string\n\nbrings all the boys to the yard'
<Text>{someText}</Text>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment