0

What I'm trying to do is in the return of a render method, to add a newline between each element of an array (of strings).

I've tried two ways (one of them is commented):

import React, { Component } from 'react'

export default class extends Component {
  render() {
    return (
      <div>
        <div>
            <div className='Dog'>
                {this.props.name}
                <p>Age: {this.props.age}</p>
                {/* <text>About: {this.props.fact.map((f) => f+'\n')}</text> */}
                <p>{this.props.fact.join('\n')}</p>
            </div>
        </div>
      </div>
    )
  }
}

The result is not what I was looking for:

image #1 - result without any of my attempts (as if - just rendering {this.props.fact}:

enter image description here

image #2 - with my attempt (both attempts end up with same result):

enter image description here

AAAAAAAAAAAH, I'm clueless!

Thanks in advance.

2 Answers 2

2

Since whitespace is largely ignored, outputting a newline (\n) won't actually insert a line break. Instead, just use the line break tag (<br>).

In JSX, that looks like <br />. Since you need to return a single element, you'll also want wrap your text and line break in a fragment (<>...</>):

<text>
    About:{" "}
    {this.props.fact.map((f) => (
        <>
            {f}
            <br />
        </>
    ))}
</text>
Sign up to request clarification or add additional context in comments.

3 Comments

Or you could flatMap into [f, <br />] if you're fancy :3
@caTS me likey likey. p.s, answer worked like a charm. thanks!
Typically you don't want the trailing <br />, though.
0

If it's just text, you could use dangerouslySetInnerHTML

<p dangerouslySetInnerHTML={{ __html: this.props.fact.join('\n') }} />

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.