Skip to content

[react] Lit Element in React Component Doesn't Apply Default Prop Value on Re-render without Property Set #4227

@rivajunior

Description

@rivajunior

Which package(s) are affected?

React (@lit-labs/react)

Description

I am currently experiencing a problem with a component's conditional rendering. During the first render, the component features a property with a particular value. However, during the subsequent render, the property is not set, and the lit element employs the previously set value instead of the default value. I would like to apologize if my explanation is vague or unclear.

Reproduction

You can see in the following sandbox that the Lit Element is expected to behave the same way as the React Component with default props. However, even though the component changes, the rendered values never change.

https://codesandbox.io/p/sandbox/gifted-dream-ptk4zn

Workaround

I have created a defaultProps option

interface Options<I extends HTMLElement, E extends EventNames = {}> {
	react: typeof React;
	tagName: string;
	elementClass: Constructor<I>;
	events?: E;
	displayName?: string;
	defaultProps?: Record<string, unknown>;
}

And used this option to set the initial value of the prevPropsRef inside the ReactComponent returned by the createComponent call.

	const ReactComponent = React.forwardRef<I, Props>((props, ref) => {
		const prevPropsRef = React.useRef<Props | null>(
			(defaultProps as Props) ?? null,
		);

I modified the createComponent function locally. Next, I created an object to set default lit element properties and pass to the options argument.

export const defaultButtonProps = {
	disabled: false,
	loading: false,
	type: 'button',
	variant: 'primary',
} as const;

createComponent({
	tagName: 'm-button',
	elementClass: MButton,
	displayName: 'Button',
	defaultProps: defaultButtonProps,
});

Is this a regression?

No or unsure. This never worked, or I haven't tried before.

Affected versions

2.0.3

Browser/OS/Node environment

Browser: Chrome 117.0.5938.92
OS: MacOS 14.0
Node: v18.18.0
NPM: 10.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions