import React from 'react';

const newlineRegex = /(\r\n|\r|\n)/g;

export default function nl2br(str: string): (string | React.ReactElement)[] {
  if (typeof str !== 'string') {
    return [str];
  }

  let counter = 0;
  return str.split(newlineRegex).map((line) => {
    if (line.match(newlineRegex)) {
      return <br key={`br-${counter++}`} />;
    }
    return <React.Fragment key={`line-${counter++}`}>{line}</React.Fragment>;
  });
}
