javascript / beginner
Snippet
Securing Controlled Form Inputs Against Script Injection
While React escapes strings inside JSX by default, sanitizing user inputs in controlled components adds an extra layer of defense against unwanted script or markup characters before storing or processing them.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useState } from 'react';function SafeCommentForm() {const [comment, setComment] = useState('');const handleChange = (e) => {const sanitized = e.target.value.replace(/[<>]/g, '');setComment(sanitized);};return (<div><input type="text" value={comment} onChange={handleChange} placeholder="Enter comment" /><p>Safe Preview: {comment}</p></div>);}export default SafeCommentForm;
react
Breakdown
1
const sanitized = e.target.value.replace(/[<>]/g, '');
Removes angle brackets from input text to neutralize basic HTML tag constructions.
2
setComment(sanitized);
Updates component state exclusively with the sanitized string.
3
<input type="text" value={comment} onChange={handleChange} placeholder="Enter comment" />
Binds the controlled input value and change event handler to state.