Skip to content

Instantly share code, notes, and snippets.

@mledwards
Last active January 8, 2021 10:01
Show Gist options
  • Save mledwards/9f602b834a315a73187998e54f1d4750 to your computer and use it in GitHub Desktop.
Save mledwards/9f602b834a315a73187998e54f1d4750 to your computer and use it in GitHub Desktop.
React component - Convert textarea new lines to paragraphs
import React from "react";
// Normalise new lines from a textarea before outputting as JSX
export const Content = ({ content, className, lastParagraphMargin = "mb-0"}) => {
// Return null if there's no content passed to the component
if (!content || content.length === 0) {
return null;
}
// Normalise the new lines across different operating systems
// Split by \n
// Filter any empty array items
const paragraphs = content.replace(/(?:\\[rn]|[\r\n]+)+/g, "\n").split("\n").filter(Boolean);
// Loop over the paragraphs array, and output as JSX
// Last paragraph may have different margin, so pass this into the component
// NOTE: mb-5 is using TailwindCSS, so alter for your needs
return paragraphs.map((paragraph, paragraphIndex) => (
<p
className={`${className} ${
paragraphIndex < paragraphs.length - 1 ? "mb-5" : lastParagraphMargin
}`}
>
{paragraph}
</p>
));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment