2

I'm trying to send following code to a child component in React js:

{
    carPhoto: "../../images/small-logo.jpg",
    make: "Mercedes",
    price: "€20000",
    desc: "Vivamus gravida magna massa in cursus mi"
}

Now I'm trying to split desc in two lines. I tried with \n, \r, \r\n

desc: "Vivamus gravida magna<br /> massa in cursus mi"
desc: "Vivamus gravida magna\nmassa in cursus mi"
desc: "Vivamus gravida magna\r\nmassa in cursus mi"

But nothing worked. Any advice?

aarosil
  • 4,848
  • 3
  • 27
  • 41
Boky
  • 11,554
  • 28
  • 93
  • 163

4 Answers4

7
<span>
 Example #1: <br /> newline
</span>
<span style={{ whiteSpace: 'pre-wrap' }}>
 {"Example #2: \r new line or \u000A new line"}
</span>
{/* do not forget add style { white-space: pre-wrap } */}
<Example3 text={"Example #2: \r new line or \u000A new line"} />
Sergey Karasev
  • 4,513
  • 4
  • 25
  • 24
2

Easy way to do white space or new line in react is create module with it like this: (and do not forget add white-space: pre or pre-wrap; for container)

// htmlCodes.js
export const nbsp = '\u00A0';
export const breakline = '\u000A';

and then use it in component or strings:

// MyComponent.jsx
import {nbsp, breakline} from './htmlCodes';

const myString = `one{nbsp}two{breakline}`;

const MyComponent = () => {
  <div style={{ whiteSpace: 'pre-wrap' }}>
    first{nbsp}second{breakline}third
  </div>
}

the best way, create component Text and use their together:

// Text.jsx
export const Text = (children) => {
  <span style={{ whiteSpace: 'pre-wrap' }}>
    {children}
  </span> 
}

// MyComponent.jsx
import {nbsp, breakline} from './htmlCodes';
import {Text} from './Text.jsx';

const MyComponent = () => {
  <div>
   <Text>one{nbsp}two{breakline}three</Text>
  </div>
}
Sergey Karasev
  • 4,513
  • 4
  • 25
  • 24
0

Very simple way with very simple component with simplest html output

and you can use it like prop

<TravelCard
      text={<BreakString
            text={"7 days \n Friends Reunion\n Historic, Touristy"} >}
/>

or

<p>
   <BreakString
      text={"7 days \n Friends Reunion\n Historic, Touristy"} />
</p>

component you should create:

const BreakString = ({ text }) => {
  const strArr = text.split("\n");
  return (
    <>
      {strArr.map((str, index) => (
        <React.Fragment key={index}>
          {str}
          {index !== str.length - 1 && <br />}
        </React.Fragment>
      ))}
    </>
  );
};

output

<p>7 days <br> Friends Reunion<br> Historic, Touristy<br></p>
Hyzyr
  • 568
  • 4
  • 13
-2

You can either use CSS, as suggested in the comments. Or you can dangerously set inner HTML using the <br/> tag:

<div dangerouslySetInnerHTML={{__html: this.props.desc}} />

It's important to note that this approach is XSS-prone, thus the name.

You can read more here: https://facebook.github.io/react/tips/dangerously-set-inner-html.html

Community
  • 1
  • 1
Sergio
  • 671
  • 5
  • 10