React TypeScript 改行が含まれれるテキストをいい感じに改行させたい
前にも同じようなことやったけど React.createElement を使った TypeScript 版を作ったのでメモ
import { ReactElement, createElement } from 'react'; const newlineRegex = /(\r\n|\r|\n)/g; export const nl2br = (text: string): (string | ReactElement)[] => { return text.split(newlineRegex).map((line, index) => { if (line.match(newlineRegex)) { return createElement('br', { key: index }); } return line; }); };
1 引数で渡された文字列 text に含まれる改行コードをキャプチャして分割
split(separator)
Ifseparatoris a regular expression that contains capturing parentheses( ), matched results are included in the array.
cf. String.prototype.split() - JavaScript | MDN
"星宮いちご\n霧矢あおい\n紫吹蘭".split(/(\r\n|\r|\n)/g); // => ['星宮いちご', '\n', '霧矢あおい', '\n', '紫吹蘭']
2 改行コードを createElement('br', { key: index }) で brタグ に変換して返す
createElement(type, props, ...children)
props: Thepropsargument must either be an object ornull. If you passnull, it will be treated the same as an empty object. React will create an element withpropsmatching thepropsyou have passed. Note thatrefandkeyfrom yourpropsobject are special and will not be available aselement.props.refandelement.props.keyon the returned element. They will be available aselement.refandelement.key.
cf. createElement – React
React.createElement の第二引数が props なので key を設定できる
やってることは同じだけど、前の React.Fragment を使う方法よりシンプルにかけた気がする
おわり ₍ ᐢ. ̫ .ᐢ ₎
[参考]

