How do I add an unknown attribute to an element in ReactJS?

There’s this project I’ve been working on in ReactJS and Chrome and I needed to use a <webview> component. In case you’re not familiar with <webview>, it looks something like this —

&lt;webview src="https://rselbach.com"&gt;&lt;/webview&gt;

One of the coolest features of <webview> is the ability to isolate scope or partition it. When you use a partition, all cookies, local and session storage, etc, will be stored separately from other partitions. All you need to do is add the partition attribute. So I had something similar to this inside one of my components —

return (
  <webview id="foo" 
  src="https://somewebsite.com/"
  partition="persist:foobar" />
);

To my surprise, multiple <webview>s were sharing the same session data. Not good. A quick glance in the app storage directory told me that no partition was being created. What’s wrong?

We can look at the HTML output for hints —

&lt;webview id="foo" src="https://somewebsite" class="MyComponent__component___3U2KV" data-reactid=".0.0.0.2:$MyComponent.0" tabindex="-1"&gt;&lt;/webview&gt;

No partition to be found. The reason is React doesn’t know what to do with that attribute and as a result it is not output. There are good reasons for this, but the main one is that properties may (and often do) work differently accross browsers and React needs to be able to deal with this.

But how can we add the attribute that we need then? You could add some JavaScript to get the element but that’s not very reactive. The reactive way to do this is to leverage ref, which can provide a reference to an element.

&lt;Element ref={somevar} /&gt;

In this code, somevar will hold a reference to <Element>. Better yet, just use a function instead.

&lt;Element ref={function(e) { e.Something(); }} /&gt;

Or in ES6 syntax.

&lt;Element ref={(e) =&gt; e.Something() } /&gt;

Which finally takes us to our problem: how do we add the partition attribute? Easy peasy.

return (
  <webview id="foo" 
  src="https://somewebsite.com/"
  ref={elm => elm && elm.setAttribute('partition', 'persist:foobar')} />
);

And that’s it, a simple way to add unknown attributes to elements in React.