Roberto Selbach

About |  Blog |  Archive

Tag: HTML

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 —

 <webview src="https://robteix.com"></webview>

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 —

 <webview id="foo" src="https://somewebsite" class="MyComponent__component___3U2KV" data-reactid=".0.0.0.2:$MyComponent.0" tabindex="-1"></webview>

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.

 <Element ref={somevar} />

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

 <Element ref={function(e) { e.Something(); }} />

Or in ES6 syntax.

<Element ref={(e) => e.Something() } />

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.