Last active
July 28, 2021 03:35
-
-
Save mayank23/f318aefcaee33595eded857550a4ee4a to your computer and use it in GitHub Desktop.
React New Lines ("\n") Example - babel / react / css (white space pre-wrap)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); |
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
In react I would use the key whiteSpace instead.