0 day streak
javascript / beginner
Snippet

Preventing XSS by Safely Rendering Dynamic String Content

By default, React treats interpolated string data inside JSX as plain text and automatically escapes special characters like < and >. This built-in security mechanism prevents malicious scripts from executing in the browser without requiring manual HTML sanitization.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import React, { useState } from 'react';
function UserComment({ rawInput }) {
const [commentText] = useState(rawInput);
return (
<div className="comment-box">
<p>User feedback: {commentText}</p>
</div>
);
}
react
Breakdown
1
const [commentText] = useState(rawInput);
Stores user-provided comment text as a standard primitive string value in state.
2
<p>User feedback: {commentText}</p>
Safely embeds string content where React automatically escapes potential HTML tags, preventing script injection.