I am getting data from a database in a form of a string for my React.js appliaction, But when I try to apply a <br>
tag to all '/n'
, I get these as part of the string and not as a line break. I have tried removing the quote marks or using a JSX <br/>
instead, but still got the same result. What should I do?
My code looks like this:
const [abt, setAbt] = React.useState();
React.useEffect(() => {
setAbt(databaseValue.replace(/\n/g, '<br>'))
}, [])
return (
{abt}
)
Thanks!
Don't put HTML in your state.
Build the DOM you want with JSX instead.
eg
const [abt, setAbt] = React.useState("");
React.useEffect(() => {
setAbt(databaseValue)
}, [])
const nodes = abt.split("\n").reduce( (acc, line) => {
if (acc) {
return [...acc, (<br />), line];
}
return [line]
}, null);
return <>{nodes}</>
… or possibly just use a <pre>
element in the first place.
Instead of saving a string, you can split it to an array and then using map
put <br>
between them during render:
function App() {
const [abt, setAbt] = useState([]);
useEffect(() => {
const string = "First\nSecond";
const splitted = string.split(/\n/)
setAbt(splitted)
}, [])
return (
<div className="App">
{abt.map(slice => <>{slice} <br></br> </>)}
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.