Ad
React: Inserting A Line Break In Localised Text
I'm getting localised text from a JSON file and displaying it to the page, my problem is that the \n
and <br>
notations are being ignored.
I've made a code sandbox here to show how the text doesn't get put on more than one line.
import * as React from "react";
import { render } from "react-dom";
const App: React.FC = props => {
const Translations: {
[key: string]: {
fname: string;
};
} = {
en: {
fname: "I want to insert a break in this line of text so it shows on two lines \n doesnt work and <br> does either",
},
cn: {
fname: "我想在这一行文本中插入一个中断,以便在两行中显示\ n不起作用,而<br>可以",
}
};
const txt = Translations["en"];
return (
<div className="App">
<p>{txt.fname}</p>
</div>
);
};
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Ad
Answer
In order to respect \n
, you can add a style of white-space: pre-line
or white-space: pre-wrap
.
In React, it would look like this:
return (
<div className="App">
<p style={{ whiteSpace: "pre-line" }}>{txt.fname}</p>
</div>
);
Here is a forked sandbox.
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad