Skip to content

Custom React components with an sx prop can’t live alongside HTML elements using the @jsxImportSource theme-ui pragma #2454

Open
@kapowaz

Description

@kapowaz

If a custom React component has an API with a prop called sx, that prop is ignored if the component is called alongside any other HTML element with an sx prop augmented using the /** @jsxImportSource theme-ui */ pragma.

To Reproduce

Let’s say I have some arbitrary JSX on a page, where I’m styling arbitrary HTML elements using the sx prop, and the /** @jsxImportSource theme-ui */ pragma:

/** @jsxImportSource theme-ui */

export default () => {
  return (
    <div sx={{ color: 'blue'; }}>
      hello world
    </div>
  );
}

Let’s also say that I have a custom React component which accepts an sx prop as part of its own API, because I want to be able to pass those styles through to some part of the component’s internal implementation:

/** @jsxImportSource theme-ui */

import React from 'react';
import { ThemeUICSSObject } from 'theme-ui';

export const MyComponent = ({
  children,
  sx,
}: {
  children: React.ReactNode;
  sx: ThemeUICSSObject;
}) => {
  return (
    <div sx={sx}>
      {children}
    </div>
  );
}

If I then try to use these two components together, like this:

/** @jsxImportSource theme-ui */
import { MyComponent } from './MyComponent';

export default () => {
  return (
    <div sx={{ color: 'blue'; }}>
      <MyComponent sx={{ color: 'red'; }>Hello World</MyComponent>
    </div>
  );
}

…I would expect this to set the inner text to have a color property of red, but instead the value passed to this inner sx prop acts as if it’s undefined:

/** @jsxImportSource theme-ui */

import React from 'react';
import { ThemeUICSSObject } from 'theme-ui';

export const MyComponent = ({
  children,
  sx,
}: {
  children: React.ReactNode;
  sx: ThemeUICSSObject;
}) => {
  // in the example above, this would output '{ sx: undefined }'
  console.log({ sx });

  return (
    <div sx={sx}>
      {children}
    </div>
  );
}

Expected behavior

I would expect the style object passed to the sx prop of the custom component to correctly be passed through to the child.

Additional context

The problem only seems to be manifest when mixing these two types of usage of the sx prop, however; if in the scope of a single source file you are exclusively passing the sx prop to custom components, or exclusively passing it to plain HTML objects, they will work (and so as a workaround we will often split up the code, but this is sometimes not convenient).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions