Render key as html property in React

Viewed 416

I'm using React and need to render meta tag with non-standard properties.

<meta name="some-name" key="some-key" values="some,values">

Since key property is special in React, React won't propagate it to children and it won't render it. How can I work around this? I know React will pass any unknown property to HTML tag but I can't use data-key (for example), I need to render key property specifically.

I'm using React Helmet and don't have control over head element therefore I can't do

<head dangerouslySetInnerHTML={{__html: '<meta key="value">'}}></head>

I also can't use React refs because I'm rendering this on server-side (and client-side) and doesn't have access to components lifecycle nor reference to DOM element.

EDIT: I modified original answer to exclude any reference to Typescript because question is about React, not Typescript.

2 Answers

You can achieve this using the following, in your doctype declaration, you can add

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
[
  <!ATTLIST tag myAttri CDATA #IMPLIED>
]>

Where myAttri is your attribute, you can name it key to match what you want.

#IMPLIED means that it's optional. If you want it on every single element, you can use #REQUIRED

You can also try setting the attribute through js with

document.getElementById("foo").myAttri = "myVal"

Related