matty_keene
matty_keene

Reputation: 198

How can I detect line breaks in string coming from state?

I'm having trouble detecting line breaks coming from a text area. The standard .replace('↵', '\n') doesn't work, because by the time I call this.state.note the return characters have been respected.

From the console:

> this.state {flashMessage: "", note: "one potato ↵two potato↵three potato↵four", showShareModal: false, isEditing: true}

> this.state.note "one potato two potato three potato four"

I've attempted to use encoudeURI and searching the string for '\n' - both with no luck.

Is there a way I can get the raw format of this.state.note?

Upvotes: 0

Views: 2309

Answers (2)

matty_keene
matty_keene

Reputation: 198

Turns out I was able to use encodeURI(this.state.note). Because my end goal was to pass this to a mailto: link, the encoded return statements get translated perfectly into %0A.

Upvotes: 0

Henry Woody
Henry Woody

Reputation: 15692

React will replace '↵' with '\n' automatically so if your textarea is controlled, your component's state should hold the text for the text area with '\n' characters included. Sending (POST) and storing the text should not remove '\n' characters, so as far as I can tell from the code you have shown, the '\n' characters are still present.

I suspect the issue is simply that HTML does not use '\n' as its linebreak character, so the new lines are not shown on the page. Instead HTML uses <br/>. Better would be to break the note into separate <p> elements. Here's how you could do that:

const splitNote = this.state.note.split('\n').map(e => <p>{ e }</p>);

You could also split note into <span> elements and then put them in a <div> with {display: flex; flex-flow: column;}. Up to you.

Note:

If, for some reason your '\n' characters are being removed somewhere, and there is no reasonable way to stop this, you could replace '\n' with '\\n' before the replacement happens. But I don't think this is a likely scenario.

Upvotes: 1

Related Questions