Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to add an attribute called "key" to a custom element but React is removing it

I'm building a static site in React (using the Gatsby framework).

The site is for a yoga studio and I need to embed a studio booking form widget onto a page. The widget is provided by a service called GymCatch. To embed their widget you must add a custom html element with an attribute called "key" - into which you paste your api key:

<gymcatch-embedded key="xxx-xxx-xxx"></gymcatch-embedded>

There is then an external javascript file that runs to replace this element with the embedded form.

The key attribute is obviously used extensively in React and is a reserved attribute name. It therefore doesn't make it to the DOM.

Can anyone think of a way that I can add this attribute to my element but not have it removed by React?

like image 466
Ben Jackson Avatar asked Oct 24 '25 08:10

Ben Jackson


2 Answers

You can use dangerouslySetInnerHTML to inject arbitrary HTML into the DOM. Obviously if this involved any user input you'd need to sanitize it first, but for this sort of thing it's safe:

const Foo = () => {
  const customtag = {
    __html: '<gymcatch-embedded key="xxx-xxx-xxx"></gymcatch-embedded>'
  };  
  
  return (
    <span dangerouslySetInnerHTML={customtag} />
  )
}

ReactDOM.render(
  (<Foo/>), document.getElementById("root")
);

// proof:
console.log(document.getElementById("root").innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 170
Daniel Beck Avatar answered Oct 26 '25 23:10

Daniel Beck


Change the letter case of key to work it out. Key, kEy, keY, KEY, either is okay.

This is because JavaScript and JSX is case-sensitive while HTML attribute is not. React has occupied key but other spellings in different letter cases haven't.

like image 26
Zhang Wei Avatar answered Oct 26 '25 21:10

Zhang Wei