5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactjsで改行コードをbrに変換する

Last updated at Posted at 2015-08-11

方法1: reactjsのdangerouslySetInnerHTMLを使う方法

参考: https://facebook.github.io/react/docs/jsx-gotchas.html

# sample.js.jsx.coffee:

# 改行コードをBRタグに変換
nl2br: (str) ->
  str.replace(/[\n\r]/g, "<br />")

render: ->
  ...
  <dd dangerouslySetInnerHTML={{__html: nl2br(this.state.report.description)}}></dd>
  ...

方法2: 改行をsplitしてjsxの配列を作成する方法

# sample.js.jsx.coffee:

# 改行コードをBRタグに変換したJSXを返す
nl2brJsx: (str) ->
  lines = []
  for line in str.split("\n")
    lines.push(`<div>{line}<br/></div>`)
  lines

render: ->
  ...
  <dd>{Utils.nl2brJsx(this.state.report.description)}</dd>
  ...
5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?