4

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?

3
  • What about using this.props.notifications.join(); ? Commented Jan 11, 2018 at 21:25
  • 1
    What do you mean by "this doesn't seem to be working"? It works in some way. What way do you want it to work? Commented Jan 11, 2018 at 21:32
  • @Aaron I want each string to be on a separate line. I tried using .join('\n') but that doesn't seem to do the trick. I updated my question. Commented Jan 11, 2018 at 21:36

3 Answers 3

14

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.

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

Comments

4

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>

1 Comment

I've tried that, but it only words if I'm mapping over an array of numbers. If I use an array of strings, it puts them all together side-by-side, even though the individual <p></p> is clearly defined
2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.