Skip to content

Instantly share code, notes, and snippets.

@mayank23
Last active July 28, 2021 03:35
Show Gist options
  • Save mayank23/f318aefcaee33595eded857550a4ee4a to your computer and use it in GitHub Desktop.
Save mayank23/f318aefcaee33595eded857550a4ee4a to your computer and use it in GitHub Desktop.
React New Lines ("\n") Example - babel / react / css (white space pre-wrap)
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
const App = () => {
return (
<div style={styles}>
<Hello name="CodeSandbox" />
<p style={{
'white-space': 'pre-wrap'
}}>{"This \n works"}</p>
<p style={{
'white-space': 'pre-wrap'
}}>Does \n not \n work</p>
</div>
);
};
/*
BABEL PLUGIN TRANSFORM-JSX OUTPUT:
const App = () => {
return React.createElement(
'div',
{ style: styles },
React.createElement(Hello, { name: 'CodeSandbox' }),
React.createElement(
'p',
{ style: {
'white-space': 'pre-wrap'
} },
"This \n works"
),
React.createElement(
'p',
{ style: {
'white-space': 'pre-wrap'
} },
'Does \\n not \\n work'
)
);
};
MODIFIED EXAMPLE WHICH WORKS:
const App = () => {
return React.createElement(
'div',
{ style: styles },
React.createElement(Hello, { name: 'CodeSandbox' }),
React.createElement(
'p',
{ style: {
'white-space': 'pre-wrap'
} },
"This \n works"
),
React.createElement(
'p',
{ style: {
'white-space': 'pre-wrap'
} },
'Does \n actually \n work'
)
);
};
*/
render(<App />, document.getElementById('root'));
@JoshOyiki
Copy link

In react I would use the key whiteSpace instead.

@mbcod3
Copy link

mbcod3 commented Jul 28, 2021

Is there a way to preserve text formating in react p tag without using template literals? I mean

<p> 
hello

bye
</p>

In react it collapses and render both of them on the same line even with white-space: pre-line.

This works though

<p>{`
hello

bye
`}</p>

Is it possible to get the same result as above without using template literals?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment