LoginSignup
2
0

React で複数行テキストを画面に表示する

Posted at

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>
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0