Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use native slots in react?

I'm trying to build a simple application with react and web components UI library. This library uses named slots in order to populate areas in the component. When trying to use a named slot like this in my template:

<div slot="app-content"></div>

The rendered output is without the slot: <div></div>

Minimal reproduction: Just add <div slot="mySlot" id="mySlottedDiv"></div> to a react component's template. Then inspect the resulting HTML and see that the slot attribute is omitted.

Here's an example of such an app: https://codesandbox.io/s/vivid-spring-hack-react-example-forked-yu9dss?file=/index.js

In this file, you can see I'm setting a div with slot="app-content" but the resulting HTML removes the attribute from the div - hence preventing me from using the web component's API.

Is there a way to force react NOT to remove attributes from an element? Is this a bug in react?

like image 202
yccteam Avatar asked Sep 21 '25 08:09

yccteam


1 Answers

It seems like there are some issues opened and closed on some libraries trying to integrate with react to support slot attribute properly.

This seems to be a solution that circumvents react whitelisted attributes:

function slot(name = "") {
  return { ref: (e) => e.setAttribute("slot", name) };
}

and then render:

 <div {...slot("app-content")}>

This seems to work.

Here there are some more info: https://github.com/skatejs/skatejs/issues/1096 https://codesandbox.io/s/vivid-spring-hack-react-example-forked-nik1hs?file=/index.js

like image 136
Cesare Polonara Avatar answered Sep 22 '25 20:09

Cesare Polonara