Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a <br> tag in reactjs between two strings?

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>
       );
   }
like image 201
Radex Avatar asked Aug 29 '17 09:08

Radex


People also ask

How do you add BR to a string?

How Can I Add a New String Line? The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do you create a line break in React?

You can use {'\n'} as line breaks.


3 Answers

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>
   );
}
like image 115
Dekel Avatar answered Oct 10 '22 00:10

Dekel


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.
like image 40
Gulfam Avatar answered Oct 09 '22 23:10

Gulfam


break text to line:

render() {
  ...
  <div>
    {this.props.data.split('\n').map( (it, i) => <div key={'x'+i}>{it}</div> )}
  </div>
  ...
like image 19
Алексей Носиков Avatar answered Oct 09 '22 23:10

Алексей Носиков