I am new to reactjs, I am trying to join which works, but I want to put a break after each Hello continent. The <br />
and n
do not work. The br
tag works in regular js but not react.
What I am looking for is
Hello Africa
Hello America
etc
What I am getting is Hello Africa Hello America ect
const continents = ['Africa','America','Asia','Australia','Europe'];
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
const message = helloContinents.join("<br />");
const element = (
<div title="Outer div">
<h1>{message}</h1>
</div>
);
3
Answers
I tried your code and what you get is
Hello Africa!<br />Hello America!<br />Hello Asia!<br />Hello Australia!<br />Hello Europe!
That because your code is producing a single
<h1>
element with the concatenatedhelloContinents
messages, separated by<br />
, but this<br />
tag will be treated as plain text and not render as a line break in React.To address this issue I suggest you to ensure that the
<br />
tags are treated as actual HTML elements.Here an example:
You’re trying to write HTML to the output, which by default is sanitized to help mitigate XSS vulnerabilities. You can use
dangerouslySetInnerHTML
to explicitly get around that:Alternatively, for the data you’re trying to display you don’t need to build up an HTML string in the first place. You can iterate over the array values and output the structure you want:
We can shorten and simplify your code with React.
With React we can significantly reduce the number of lines of code, here we allowed React to handle the joining of
strings
witharray
values.key
is required for each element here as we are returning a list of html elements usingArray.map()
and needs an unique string as a value, it allows react to uniquely identify each element.If your requirement is still for using
<br/>
, you can add the tag like{continent}<br/>
.React uses JSX – JavaScript Syntax Extension. It allows developers to write HTML-like code in JavaScript files.