1

I want to put linebreaks in a placeholder for a textarea. According to this question & answer, I should add html entity 
 wherever I want a line break. This seems to work when I try it in just HTML. However, I'm losing something when I try to put this in react / quite possibly in the translation from text -> javascript variable -> react rendered html.

Here's my code:

 <textarea rows='6' defaultValue={this.state.text} placeholder={'Hello &#10; World; &#10; ' + 'How is it going?'} onChange={this.handleChange}> </textarea> 

However when I render this, the literal text &#10; shows up rather than a line break. If I edit it with inspect element, they all show up correctly after I make any change.. I'm putting this in a "{}" variable here because it's a fairly long multiline string I want to put in the placeholder value.

I'm still working through some of the variants to figure out the smallest reproducible example / if any simple changes fix it, but my react turnaround time is not great. Would appreciate it if anyone is able to reproduce, has run into this before, or knows more about html entities & javascript string rendering.

1 Answer 1

2

Ok, it seems like "put HTML entities in a react string" was indeed the important part here. This question:

Render HTML entities inside a string in React

answered that & recommended using ${String.fromCharCode(some_code)} . From there I found &#10 is the "line feed" character, with ASCII code 10. So I swapped my code to:

let lb = String.fromCharCode(10); let toRender = ( <textarea rows='6' placeholder={`Hello ${lb}World${lb}` + 'How is it going?'} onChange={this.handleChange}> </textarea>); 

& it now renders as expected, with line breaks in the placeholder.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is the proper solution. It also works e.g. for the non-breaking space (charcode 160), I even have export const nbsp = String.fromCharCode(160); in many of my React apps. As an aside, charcode 10 is usually identified as the LineFeed character, so I'd suggest naming it lf instead of lb. And using const instead of let would be even more proper.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.