88

I am using react. I want to add a line break <br> between strings

'No results' and 'Please try another search term.'.

I have tried 'No results.<br>Please try another search term.'

but it does not work, I need to add the <br> in the html.

Any ideas how to solve it?

   render() {
       let data = this.props.data;
       let isLoading = this.props.isLoading;
       let isDataEmpty = Object.entries(data).length === 0;
       let movieList = isLoading ? <Loader /> : isDataEmpty ? 'No results. Please try another search term.' :
           Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
       return (
           <div className='movieList'>{movieList}</div>
       );
   }
Radex
  • 7,815
  • 23
  • 54
  • 86

13 Answers13

98

You should use JSX instead of string:

<div>No results.<br />Please try another search term.</div>

Because each jsx should have 1 wrapper I added a <div> wrapper for the string.

Here it is in your code:

render() {
   let data = this.props.data;
   let isLoading = this.props.isLoading;
   let isDataEmpty = Object.entries(data).length === 0;
   let movieList = isLoading ? <Loader /> : isDataEmpty ? <div>No results.<br />Please try another search term.</div> :
       Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
   return (
       <div className='movieList'>{movieList}</div>
   );
}
Dekel
  • 60,707
  • 10
  • 101
  • 129
  • 1
    ?? Does not work for me. in the return method of render, i have
    {this.state.myErrorString}
    , where myErrorString itself begins with a
    and ends with a
    and has
    inside it, and all the tags displays !
    – joedotnot Apr 20 '19 at 06:05
  • @joedotnot does `myErrorString` is a string or a jsx object? – Dekel Apr 21 '19 at 10:27
  • It is a string; For example: this.setState({myErrorString : "
    it is a string.
    continue here
    "}) which I then render inside jsx; For example: render() { return
    {this.state.myErrorString}
    }
    – joedotnot Apr 21 '19 at 11:03
  • 1
    It looks like let movieList = a jsx object ! So how do i transition from a string in state into a jsx object? – joedotnot Apr 21 '19 at 11:08
  • 1
    This is a complete different question. Why are you using a string on the first place instead of a jsx object? – Dekel Apr 21 '19 at 13:15
  • Because it never occurred to me that i can use jsx in react state (can I?). I've only used strings, arrays, objects, etc.. and reserve jsx to be used within the render part. But maybe I can proceed as per your example.. render string to a jsx wrapper first, then return the jsx wrapper – joedotnot Apr 21 '19 at 13:40
82

You can use CSS white-space to solve the problem.

React Component

render() {
   message = `No results. \n Please try another search term.`;
   return (
       <div className='new-line'>{message}</div>
   );
}

CSS

.new-line {
  white-space: pre-line;
}

OUTPUT

No results.
Please try another search term.
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Gulfam
  • 829
  • 6
  • 2
  • 5
    The best way to fix! – Dayglor Jun 09 '20 at 21:23
  • 2
    This should be the one and only and accepted answer – T.Chmelevskij Mar 03 '21 at 13:52
  • 3
    new to react, so my line of thinking is: how would i add a line break in pure html? then why do i have to create this contrived class to add a new line in react? – Nilesh Jul 20 '21 at 18:01
  • 2
    Nice one! I recommend this method. – Yohan W. Dunon Aug 10 '21 at 14:06
  • 1
    @Nilesh there's no need to add a line break tag in HTML when CSS can simply show the **literal line breaks** in the content. In React, all text content is sanitized, so it's more difficult to output text (from a source you don't control) with HTML line breaks unless you do some Javascript parsing (overkill for a small problem) or you use `dangerouslySetInnerHTML` (dangerous with user input). – ADTC Nov 03 '22 at 08:45
  • documenting this answer. – Nagama Inamdar Nov 22 '22 at 12:15
19

break text to line:

render() {
  ...
  <div>
    {this.props.data.split('\n').map( (it, i) => <div key={'x'+i}>{it}</div> )}
  </div>
  ...
15

Some HTML elements such as <img> and <input> use only one tag. Such tags that belong to a single-tag element aren't an opening tag nor a closing tag. Those are self-closing tags.

In JSX, one has to include the slash. So, remove <br> and try <br />

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
mengru zhang
  • 379
  • 3
  • 9
10

Here is how I got around this. Let message be the prop/variable that has the string containing line breaks to be displayed in HTML as follows:

message = 'No results.<br>Please try another search term.';
<div>
  {message}
</div>

To make this work, we need to use \n instead of break tag <br> and set the following css on the wrapper element of this message as follows:

message = 'No results.\nPlease try another search term.';
<div className="msg-wrapper">
  {message}
</div>

CSS:

.msg-wrapper {
  white-space: pre-wrap;
}

OUTPUT:

No results.
Please try another search term.
Peter
  • 10,492
  • 21
  • 82
  • 132
4

If you don't want put the string inside a <div> you could use <> to do it.

Like this:

var text = <>This is a text in the first line;<br />this is a text in a second line</>;
3

Just split text by /n, I do this in this way:

<div>
    {text.split('\n').map((item, i) => <p key={i}>{item}</p>)}
</div>
Idan
  • 3,604
  • 1
  • 28
  • 33
1

Try with span

return (
           <div className='movieList'><span>{movieList}</span></div>
       );
Sankar
  • 6,908
  • 2
  • 30
  • 53
1

If you are like in my situation and you don't want to add css, you can do that :

render () {
...
return (
...
<Typography component="p">
...
{(contact.lastname)?<div>Hello {contact.firstname} {contact.lastname}</div>:''}
...
</Typography>
...
);
}
Flavien M.
  • 21
  • 5
0

using `
worked for me however i am not sure if it is the exact solution to the problem :

 import React from 'react';
import ReactDOM from 'react-dom';

let element = (
<div>
  <h1> Hello world</h1>
  This is just a sentence <br></br>
  But This line  should not be in the same previous line. <br></br>
  The above content proves its working. <br></br>
  npm v6.14.6 | react : {React.version} 
</div>
);

ReactDOM.render(element,document.getElementById("html-element-id"))

ansh sachdeva
  • 1,220
  • 1
  • 15
  • 32
0

You can add a span tag and add block as a class.

Pomodoro Technique Timer <span className="block">with Bla</span>
Mario Callejas
  • 101
  • 1
  • 2
0

The simplest thing which I did is by creating a component.

const EmptySpace = ({ spaceCount = 0 }) => {
  return (
    <>
      {Array.from({ length: spaceCount }, (item, index) => {
        return <br key={index} />;
      })}
    </>
  );
};

export default EmptySpace;
<EmptySpace spaceCount={1} />

In your case you could do something like this:

const msg = (
    <p>
      No results <EmptySpace spaceCount={2} />
      Please try another search term.
    </p>
  );
maazu
  • 21
  • 1
  • 2
  • 8
0

can pass the content as an array ref: https://reactjs.org/docs/jsx-in-depth.html

Page

import MyComponent from './components/myComponent';

export default function Page() {
  return(
        <div>
            <MyComponent
              content= {["Line 1", <br/>,  "Line 2", <br/>, "Line 3"]}
            />
        </div>
  )
}

React Component

export default function MyComponent(props) {
  return (
    <p>
        {props.content}
    </p>
  )
}

OUTPUT

Line 1
Line 2
Line 3
dingnanco
  • 1
  • 1