I'm trying to display an array of strings on separate lines in my react component by doing the following:
<div>
{this.props.notifications.join('\n')}
</div>
However, this doesn't seem to be working. this.props.notifications is an array of strings that I want to render in the div. Does anyone know how I can work around this?
I'm trying to display an array of strings on separate lines in my react component by doing the following:
<div>
{this.props.notifications.join('\n')}
</div>
However, this doesn't seem to be working. this.props.notifications is an array of strings that I want to render in the div. Does anyone know how I can work around this?
Share Improve this question edited Jan 11, 2018 at 21:36 blazerix asked Jan 11, 2018 at 21:19 blazerixblazerix 8604 gold badges12 silver badges26 bronze badges 3 |3 Answers
Reset to default 13What about using a <p />
to render each line?
<div>
{this.props.notifications.map(txt => <p>{txt}</p>)}
</div>
That will render each element in a different paragraph.
I want each string to be on a separate line.
Use Array/map()
in your render:
<div>
{ this.props.notifications.map(notification => <p>{ notification }</p>) }
</div>
You can use string literals or \n
.
But you will need to combine it with the css rule:
white-space: pre-line;
Here is a running example with string literals:
const arr = ['this is line #1', 'this is line #2', 'this is line #3']
const App = () => (
<div className="line-break">
{
arr.map(str => {
return(`
${str}
`)
})
}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
.line-break {
white-space: pre-line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Here is a running example with \n
:
const arr = ['this is line #1', 'this is line #2', 'this is line #3']
const App = () => (
<div className="line-break">
{
arr.join('\n')
}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
.line-break {
white-space: pre-line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
this.props.notifications.join();
? – gokcand Commented Jan 11, 2018 at 21:25