blazerix
blazerix

Reputation: 860

How to display an array of strings in react component

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?

Upvotes: 3

Views: 42348

Answers (3)

Aaron Beall
Aaron Beall

Reputation: 52143

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>

Upvotes: 4

Crysfel
Crysfel

Reputation: 8158

What 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.

Upvotes: 13

Sagiv b.g
Sagiv b.g

Reputation: 31024

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>

Upvotes: 2

Related Questions