I have a React component, to whose props I want to assign a string that includes both JavaScript variables and HTML entities.
Some of the approaches I've attempted have resulted in the HTML entity being rendered escaped. For example, –
gets rendered literally as "–
" instead of as "–
".
Is there a way to get an HTML entity to render unescaped in a JSX dynamic content block being assigned to a React props?
Attempts Made
Tried using a template literal:
<MyPanel title={`${name} – ${description}`}> ... </MyPanel>
Problem: In the rendered output, the –
is being rendered literally as "–
" instead of as "–
".
Attempted to construct some simple JSX with no quotes:
<MyPanel title={{name} – {description}} ... </MyPanel>
Problem: This failed at compile time with a syntax error.
Tried working around the syntax error by wrapping the JSX in a <span />
element:
<MyPanel title={<span>{name} – {description}</span>} ... </MyPanel>
Problem: This works, but I'd rather avoid the superfluous <span />
element being present in the rendered output.
Tried replacing the HTML entity with a Unicode numeric character reference:
<MyPanel title={name + ' u2013 ' + description} ... </MyPanel>
Problems:
- This works, but (in my opinion) makes the code a little less
readable. (It's more obvious that "ndash" rather than "2013"
represents an en-dash character.)
- Also, this involves
+
-operator concatenation, which triggers a Unexpected string concatenation prefer-template
error in my team's JSLint checker; a solution that uses string interpolation instead would be better.
question from:
https://stackoverflow.com/questions/65893251/html-special-character-in-react-ternary-conditional 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…