Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe string output in React ecosystem

If you want to display a string like °F in a React view as °F, I've found the documented way to do this as something like:

import React from 'react';

export default function renderSafeHTML(rawHTML, element = 'div') {
  return React.createElement(element, {
    dangerouslySetInnerHTML: {
      __html: rawHTML
    }
  });
}

And use as something like:

{renderSafeHTML('°F')}

Is there any sort of helper in the ecosystem for simplifying escaped content? Ember has {{content}} for escaping and {{{content}}} for displaying content w/o escaping and .safeString for marking strings as safe.

Is there something like that in React? I'd be curious about trying to add this functionality to JSX as {} and {{}}, similar to Ember. Why doesn't this exist in React?

like image 382
typeoneerror Avatar asked Jul 17 '26 16:07

typeoneerror


2 Answers

I am using react 16x

You don't need a helper for unicode - you can embed unicode characters directly in JSX

<h1>40{'\u00B0'}F</h1>

or

<h1>40&deg;F</h1>

This will tell you everything you need to know:

https://shripadk.github.io/react/docs/jsx-gotchas.html#html-entities

like image 68
lfender6445 Avatar answered Jul 19 '26 04:07

lfender6445


I believe React wants you to know its dangerous. They want you to go to the effort of typing all of that out. They don't want to make it easier.

This is taken from their docs:

In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

like image 28
Derek Hopper Avatar answered Jul 19 '26 06:07

Derek Hopper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!