Home » Reactjs » ReactJS render string with non-breaking spaces

ReactJS render string with non-breaking spaces

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have some props that has a string that could contain characters such as &.
It also contains spaces. I want to replace all spaces with  .

Is there an easy way I can do this? Bear in mind that I cannot just render using this syntax:

<div dangerouslySetInnerHTML={{__html: myValue}} />

because I would first have to replace any HTML entities with their markup. I don’t want to have to do this, it seems too low level.

Is there a way I can do this?

Answers:

Instead of using the &nbsp; HTML entity, you can simply use the Unicode non-breaking space character:

<div>{myValue.replace(/ /g, "\u00a0")}</div>

Questions:
Answers:

I know this is an old question, and this doesn’t exactly do what you asked for, but rather than editing the string, what you want to achieve is probably be solved better using the CSS white-space: nowrap attribute:

In html:

<div style="white-space: nowrap">This won't break lines</div>

In react:

<div style={{ whiteSpace: 'nowrap' }}>{myValue}</div>

Questions:
Answers:

If you want to display a pretty xml:

var str = "<test>\n\t\t<value>1</value>\n</test>\n".replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\t/g, "\u00a0").replace(/\n/g, '<br/>');
return (
    <div dangerouslySetInnerHTML={{__html: str}} ></div>
)

Questions:
Answers:

So you have a value like this “Hello world”, and we’ll say it’s in this.props.value.

You can do this:

var parts = this.props.value.split(" "), array = [];
for (var i=0; i<parts.length; i++){
  // add the string
  array.push(<span key={i * 2}>{parts[i]}</span>);
  // add the nbsp
  array.push(<span key={i * 2 + 1}>&nbsp;</span>);
}

// remove the trailing nbsp
array.pop();

return <div>{array}</div>;

jsbin