When working on a React project, you might encounter this ESLint error:
'`’` can be escaped with `'`, `‘`, `'`, `’`. eslintreact/no-unescaped-entities
eslint(react/no-unescaped-entities) error
Although your code might still work, this error appears because the react/no-unescaped-entities rule aims to prevent unintended issues with unescaped characters in JSX. Let’s dive into why this happens and how to resolve it.
Why Does This Error Occur?
The problem arises because JSX, while resembling HTML, is actually a syntax extension of JavaScript. JSX is converted to React.createElement function calls under the hood. This means JSX syntax must adhere to JavaScript's string and attribute rules.
For example:
<p>Let's make magic</p>
The single quote (') in Let's can confuse the JSX parser, as it might think the string ends prematurely. This can result in syntax errors or unexpected behavior.
What Are Delimiters?
Delimiters are characters or sequences that define boundaries in text, data, or code. JavaScript uses various delimiters:
const string = "Hello, world!"; // Double quotes as delimiters
const array = [1, 2, 3]; // Square brackets as delimiters
const regex = /hello/; // Forward slashes as delimiters
In JSX, single or double quotes act as delimiters for attributes:
const text = 'I know because I'm outside'; // Error: Unescaped single quote
<Card title='It's raining' text={text} />; // Error: Unescaped single quote
Here, the single quote inside the strings (I’m) and (It's) prematurely ends the attribute, causing a syntax error.
Delimiters, examples and usage
How to Resolve the Error
There are several ways to handle this issue:
HTML Entities
Escape special characters using HTML entities:
'or'for single quotes‘for left single quotation marks
<Card title='Let's make magic' />
<p>Let's make magic</p>
Using Double quotes
Double quotes can enclose strings with single quotes:
<Card title="Let's make magic" />
Escape with backslash
Use a backslash (\) to escape single quotes in JavaScript strings:
const text = "Let's make magic";
Using Template Literals
Template literals in JavaScript allow single quotes without escaping:
const text = `Let's make magic`;
Conclusion
The react/no-unescaped-entities rule ensures clean and error-free JSX. By escaping special characters or using double quotes, template literals, or backslashes, you can resolve these errors effectively. Understanding the nuances of JSX and JavaScript will help you write better React code.