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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With