Created
April 17, 2018 06:22
-
-
Save willhackett/210a9441d12b54f2f4ae6d62300c79aa to your computer and use it in GitHub Desktop.
Line breaks & Paragraphs in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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