I'm having trouble with new line breaks in strings.
parent
<SampleComponent title="One \n Two \n Three">
children
type SampleComponentProps = {
title: string;
};
export const SampleComponent: FC<SampleComponentProps> = ({
title,
}) => {
return (
<div style={whiteSpace:'pre-line'}>{title}</div>
);
};
display
One \n Two \n Three
I would expect
One
Two
Three
CodePudding user response:
The following code should work
return ({title.split("\\n").map((line, index) => (
<React.Fragment key={index}>
{line}
<br />
</React.Fragment>
))})
CodePudding user response:
You can solve this problem by setting HTML directly from React, just using html and css, no using JS regex, or convert string to array then output.
<div
style={{whiteSpace: 'pre'}}
dangerouslySetInnerHTML={{ __html: ' One \n Two \n Three' }}
></div>
this is the result
Reference link: dangerously set innerHTML