乐闻世界logo
搜索文章和话题

How to add a < br > tag in reactjs between two strings?

1个答案

1

In ReactJS, when working with strings and inserting HTML tags such as <br> between them, it's important to note that directly inserting HTML into strings may not render as expected because React defaults to escaping strings to prevent XSS attacks (Cross-Site Scripting). To safely insert HTML, we can use the dangerouslySetInnerHTML attribute, or more commonly, use JSX to combine strings and HTML tags.

Method 1: Using JSX to Combine Strings and HTML Tags

This is a safe and commonly used method. An example of inserting <br> between two strings is as follows:

jsx
function App() { const string1 = "Hello"; const string2 = "World"; return ( <div> {string1}<br />{string2} </div> ); }

In this component, string1 and string2 are wrapped within a <div> element, and <br /> is directly inserted between them using JSX. This approach safely adds a line break between two strings, and React will correctly render the <br /> tag.

Method 2: Using dangerouslySetInnerHTML

If you need to insert HTML from a single string, you can use dangerouslySetInnerHTML, but use it with caution as it may make your application vulnerable to XSS attacks. An example is as follows:

jsx
function App() { const combinedString = "Hello<br />World"; return ( <div dangerouslySetInnerHTML={{ __html: combinedString }}></div> ); }

This code renders the combinedString as HTML, including the <br /> tag. However, using dangerouslySetInnerHTML requires ensuring the content is safe to avoid malicious content injection.

Summary

It is recommended to use the first method (using JSX), as it is safer and the standard practice for combining HTML and strings in React. If you must generate HTML content directly from strings, ensure the content is safe, or use libraries like dompurify to sanitize the content before using dangerouslySetInnerHTML.

2024年6月29日 12:07 回复

你的答案