overreactedby

Why Do React Elements Have a $$typeof Property?

December 3, 2018

Pay what you like

You might think you're writing JSX:

<marquee bgcolor="#ffa7c4">himarquee>

But really, you're calling a function:

React.createElement(
/* type */ 'marquee',
/* props */ { bgcolor: '#ffa7c4' },
/* children */ 'hi'
)

And that function gives you back an object. We call this object a React element. It tells React what to render next. Your components return a tree of them.

{
type: 'marquee',
props: {
bgcolor: '#ffa7c4',
children: 'hi',
},
key: null,
ref: null,
$$typeof: Symbol.for('react.element'), // Who dis
}

If you used React you might be familiar with type, props, key, and ref fields. But what is $$typeof? And why does it have a Symbol() as a value?

That's another one of those things that you don't need to know to use React, but that will make you feel good when you do. There's also some tips about security in this post that you might want to know. Maybe one day you'll write your own UI library and all of this will come in handy. I certainly hope so.


Before client-side UI libraries became common and added basic protection, it was common for app code to construct HTML and insert it into the DOM:

const messageEl = document.getElementById('message');
messageEl.innerHTML = '

' + message.text + '

';

That works fine, except when your message.text is something like ''. You don't want things written by strangers to appear verbatim in your app's rendered HTML.

(Fun fact: if you only do client-side rendering, a