🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Web Components in React: Wrapping Custom Elements

React AdvancedđŸŸĸ Free Lesson

What You'll Learn

  • 1State which React props become attributes and which are silently ignored
  • 2Attach element events that do not exist in the React event system
  • 3Control a custom element correctly by writing properties rather than attributes
  • 4Handle definition timing, styling and typing when publishing an element for React apps

Teams that maintain a design system used by React, Vue and a legacy Angular app eventually reach the same conclusion: the shared widgets should be framework-neutral. Web components are the native answer — custom elements with shadow DOM are defined once by the browser and work everywhere — and React can consume them directly. The integration is not automatic, though. React's rules for turning props into attributes differ from what most element authors expect, custom events do not exist in React's synthetic system, and a component that displays text will happily render the string undefined the first time it mounts if you treat attributes like properties.

What React actually does with a custom element

When React renders an element whose tag is not a known HTML tag, it applies a specific conversion. If a prop is a string, number or boolean, React sets it as an attribute, converting the name from camel case to dashed form, so a propName of maxLength becomes max-length and isLowercase becomes is-lowercase. If a prop is an object, an array or a function, React skips the attribute entirely — unless the custom element is registered before React renders it, in which case React 19 and recent versions assign these values as properties on the element instance.

That single rule explains most integration bugs. A wrapper that passes a configuration object works in production because the definition loads early, and fails in development where the registration happens after the first render, leaving the element with no configuration and no error. Handlers passed as props suffer the same fate: React only wires onClick-style names to addEventListener, so an element that emits onSelectionChange receives nothing.

You passReact setsElement seesReliable?
StringAttribute with dashed nameString in getAttributeAlways
NumberAttribute with dashed nameString, needs parsingAlways, but as text
Boolean trueAttribute with dashed nameAttribute presentYes
Boolean falseAttribute removedAttribute absentYes, but see the note below
Object or arrayProperty, only if registered firstThe live valueTiming dependent
Function as onSomethingaddEventListener for somethingAn event listenerOnly for event-like names

The false case is worth calling out. Because the attribute is simply removed, an element that reads the attribute during construction sees nothing rather than false, which is correct for optional flags and wrong for anything where absence means the opposite of false. Authors should document absence explicitly, and React consumers should prefer a string attribute with explicit values when the semantics matter.

Events React has never heard of

React's synthetic event system knows the events the DOM has always had. Anything an element emits with a custom name must be attached manually through a ref, and the listener must be attached after the element exists and removed when it goes away. A thin wrapper that owns the ref is the right place, because it lets the rest of the application use a normal prop instead of remembering lifecycle details.

import { useEffect, useRef } from 'react';

export const ChartElement = (props) => {
  const { onSelectionChange, onRangeChange, series, ...rest } = props;
  const ref = useRef(null);

  useEffect(() => {
    const node = ref.current;
    if (!node) return undefined;

    const handleSelection = (event) => onSelectionChange && onSelectionChange(event.detail);
    const handleRange = (event) => onRangeChange && onRangeChange(event.detail);

    node.addEventListener('selectionchange', handleSelection);
    node.addEventListener('rangechange', handleRange);

    return () => {
      node.removeEventListener('selectionchange', handleSelection);
      node.removeEventListener('rangechange', handleRange);
    };
  }, [onSelectionChange, onRangeChange]);

  useEffect(() => {
    if (ref.current) ref.current.series = series;
  }, [series]);

  return <react-chart ref={ref} {...rest} />;
};

Notice the split. The series array is assigned as a property in an effect, because an element that renders a chart needs the live array rather than a stringified version of it, while the remaining props are left to React's attribute handling. Event names in the wrapper are camel case because that is what JavaScript callers expect, and the mapping from prop name to event name stays inside the wrapper where it can be tested once.

Attributes are strings, and that changes your component

Every attribute value crosses a string boundary. An element that displays a number gets text, so it must parse it and decide what to do with an empty string or a value that is not a number at all. Authors usually guard with a fallback, but the fallback hides configuration mistakes: a typo in a prop name produces the default value instead of a warning, and the application looks correct while showing the wrong threshold.

The defensive habit that pays off is a single normalisation point. Parse numbers with Number and check for NaN, convert missing attributes to undefined rather than to the string undefined, and validate enums against a known list so an unexpected value fails loudly in development. On the React side, give the wrapper prop types that match what the element accepts, so a mistake is caught by the compiler instead of at runtime by the chart.

Styling across the shadow boundary

Shadow DOM encapsulates styles, which is the point and also the friction. Global application CSS cannot reach inside, so a design system has to expose two deliberate seams. Custom properties are the primary one: the element reads a variable with a fallback, and the host page sets it on the element or an ancestor, letting themes flow in without the element knowing about them. The part selector is the second: the element marks an internal element with a part name, and the host styles it with a pseudo element targeting that part, which is powerful enough to restyle a button inside a third-party picker.

Neither seam works if the element hard-codes colours in its own stylesheet. Publishing a variable map alongside the element is part of shipping it, and so is documenting which parts are safe to target — parts are a public API that cannot be renamed without breaking consumers.

Registration timing and server rendering

An element definition is a promise as much as it is a class. Scripts load out of order, a bundle may register the element after React has rendered its first frame, and on the server no definition exists at all. Two habits solve this. Check before rendering with a helper that awaits the definition, or render a placeholder until custom elements define the tag you need. And guard registration so a double-loaded script does not throw on a duplicate definition.

import { useEffect, useState } from 'react';

export async function whenDefined(tag, loader) {
  if (customElements.get(tag)) return;
  try {
    await customElements.whenDefined(tag);
  } catch (error) {
    await loader();
    await customElements.whenDefined(tag);
  }
}

export function useElementDefined(tag) {
  const [defined, setDefined] = useState(() => Boolean(customElements.get(tag)));

  useEffect(() => {
    let cancelled = false;
    customElements.whenDefined(tag).then(() => {
      if (!cancelled) setDefined(true);
    });
    return () => {
      cancelled = true;
    };
  }, [tag]);

  return defined;
}

Server rendering deserves a specific decision. An element that renders meaningful markup on the server needs its definition available to the server bundle, which usually means importing the module directly rather than loading it from a script tag on the client. An element that is pure client furniture — a map, a chart, a code editor — should render a skeleton on the server and mount afterwards, so hydration sees the same shape on both sides.

Publishing for React consumers

Packaging is where otherwise good elements fail adoption. Ship an ES module entry point so bundlers can tree-shake, mark the package side-effect free only if registration genuinely does not need to run, and provide TypeScript definitions that describe the attributes as properties with correct types. Include an events map in the types so an editor offers autocomplete for onSelectionChange rather than leaving callers to read documentation.

Finally, test the element from a React application, not only from a plain HTML page. The plain page exercises the browser; the React app exercises attribute conversion, event attachment, the double mount in development, and the cleanup path when the wrapper unmounts mid-interaction. Those four are where every integration bug in this lesson comes from.

Common Mistakes

Passing an options object as a prop and assuming it reaches the element

Fix: Assign the value as a property through a ref after the definition exists

Listening for custom events only through an onSomething prop

Fix: Attach and detach addEventListener in an effect inside the wrapper

Letting a missing prop render as the text undefined inside the element

Fix: Normalise absent values to nothing and document how absence behaves

Hard-coding colours inside the shadow stylesheet

Fix: Read custom properties with fallbacks and expose a documented part map

Best Practices

  • Keep event names and prop mappings inside one wrapper so consumers never touch refs
  • Parse attribute strings at the boundary and fail loudly on unexpected values
  • Await the element definition before rendering or show a skeleton in the meantime
  • Publish TypeScript types that include both attributes and custom events
  • Verify the wrapper inside a real React app, including development double mounting

Key Takeaways

  • React converts string props to dashed attributes and ignores objects and arrays unless the element is already registered
  • Custom events bypass React entirely and must be wired through refs with explicit cleanup
  • Properties and attributes are different channels; charts and inputs generally need the property
  • Registration timing is the root cause of configuration that works in one build and fails in another
  • Styling across shadow DOM requires custom properties and part selectors declared as a public contract
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement