Web フロントエンドを書いていたら誰もが一度は作る「改行文字を <br/>
に変換するやつ (いわゆる nl2br)」を懲りずにまた再発明してしまったのでメモしておく。
import { createElement, type ReactNode } from 'react'
const nl2br = (text: string): ReactNode[] =>
text
.split('\n')
.map((line, index) => [line, createElement('br', { key: index })])
.flat()
.slice(0, -1)
使い方
const text = "複数行の\nテキスト"
return <p>{nl2br(text)}</p>