No line break when passing value containing "n" received from server side to textarea

Stack Overflow Asked by ken setoguchi on August 18, 2020

No line break when n is passed as initial value of textarea


  defaultValue={text} // "text" is the string received from the server side

enter image description here


  • Success if I pass the initial value directly on the client side instead of the value received from the server side

enter image description here

library & Framework

  • React.js
  • axios
  • styled-components

One Answer

If you are using a native browser textarea include a carriage return

  defaultValue={text.replace('\n', 'rn')}

If you are using a contenteditable component, replace n with <br />, and after you fetch it later on from the server, React will not immediately output your <br /> tags as HTML.

You will need to use dangerouslySetInnerHTML in order for the <br /> elements to reflect in the front-end as HTML elements.

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

This assumes

Answered by 95faf8e76605e973 on August 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP