0

So I am wanting a single string to display over multiple lines, something like this:

const str = "Hi\n\there\nBob"
let jsxElement = (<div>{str}</div>)

Should display jsxElement like this:

Hi
there
Bob

I have tried \n and \r\n and &nbsp and <br> and <br />. Any ideas?

BruceM
  • 1,549
  • 1
  • 18
  • 41

3 Answers3

1

You can do this using <React.Fragment> like this:

  render() {
    const test = "Hi\n\there\nBob";
    return (
      <div>
        {test.split('\n').map((item, index, arr) => {
            return <React.Fragment>
              {item}{index < arr.length - 1 && <br/>}
            </React.Fragment>
        })}       
      </div>
    )
  }
Sami Hult
  • 3,052
  • 1
  • 12
  • 17
-1

You cannot set insert string containing html directly instead you will have you use dangerouslySetInnerHTML attibute to which you want to append html as string

<div dangerouslySetInnerHTML={{__html:"Line1</br>Line2</br>Line3"}}></div> 

Second method to do this is to you use this function

  appendMiltilineString = (str) => {
    str = str.split('\n')
    return (<>
        {str.map(line=>
        (<>
            {line}<br></br>
        </>))}
      </>)
  }
 {this.appendMiltilineString('Line1\nLine2\nLine3')}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
-1

\n will not work when you put it in div.I see that you want individual word to be displayed in each line. One way i will do it is split the string with space(" ") and map the resultant array. Something like this.

  let splitArray = str.split(" ");
  splitArray.map( (s) => (
          <div>{s}</div>
 ))

you can also use <Fragment> if you don't like multiple divs to be generated.

Ron Daulagupu
  • 423
  • 6
  • 18