Skip to content

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

Closed

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

Activity

  1. justinfagnani commented on Sep 26, 2023

    @justinfagnani
    Collaborator

    When a property is no long present in the pros object, there's really no way to "remove" it from the element. The best we could do here is set it to undefined, though we would have to remember previous values in order to do that.

  2. justinfagnani commented on Sep 26, 2023

    @justinfagnani
    Collaborator

    I like the defaults idea though... we have been considering something similar for restoring a value when you remove an attribute. If we add that then maybe React wrappers could utilize it automatically.

  3. augustjk commented on Sep 26, 2023

    @augustjk
    Member

    This is a good observation/report, and due to a fundamental difference in how we treat "default" values in LitElement. The "default" are really just initial values set on element construction only, and not used in subsequent updates. We'd need to store this initial/default value separately, add logic in lit-html to detect the "removal" of an attribute/property on update and revert to default value.

    The workaround at the wrapper creation layer is clever but not ideal as it requires duplicating the default props in the option.

    We should at the very least document this behavior in the React integration docs, as it's different to what a React developer would expect.

  4. augustjk commented on Sep 28, 2023

    @augustjk
    Member

    Another workaround on the consumer side without modifying the wrapper generator code is to simply wrap it with another React component that defaults the prop like this: https://codesandbox.io/p/sandbox/falling-rain-vw3cww?file=%2Fsrc%2FMyComponentWrapped.tsx

  5. rivajunior commented on Sep 28, 2023

    @rivajunior
    ContributorAuthor

    Another workaround on the consumer side without modifying the wrapper generator code is to simply wrap it with another React component that defaults the prop like this: https://codesandbox.io/p/sandbox/falling-rain-vw3cww?file=%2Fsrc%2FMyComponentWrapped.tsx

    The "problem" with this approach is that the createComponent handles the forwardRef, so to have access to the component ref, we would have to replicate the forwardRef handling being made on the createComponent it would require a lot of boilerplate code.

  6. rivajunior commented on Sep 28, 2023

    @rivajunior
    ContributorAuthor

    The workaround at the wrapper creation layer is clever but not ideal as it requires duplicating the default props in the option.

    I've managed to reduce the duplication by using another strategy.

    // content of the createComponent function
    
    type Constructor<T> = { new (): T; defaultProps?: Partial<T> };
    
    // omitting code for brevity
    
    const ReactComponent = React.forwardRef<I, Props>((props, ref) => {
    	const prevPropsRef = React.useRef<Props | null>(
    		(elementClass.defaultProps as Props) ?? null,
    	);
    	// omitting code for brevity
    })
    export class Component extends LitElement {
    	static defaultProps: Partial<Component> = {
    		someProperty: 'someDefaultValue',
    	} as const;
    	constructor() {
    		super();
    
    		this.someProperty = Component.defaultProps.someProperty;
    	}
    }

    Kudos to @welingtonms who suggested this approach.

    I was previously creating a const defaultComponentNameProps = { /* props and values here */ } as const and passing this constant as an argument to my custom createComponent function and manually setting each property value based on this object in the class constructor.

    PS: The project I'm working on is not using decorators.

  7. augustjk commented on Sep 28, 2023

    @augustjk
    Member

    Indeed consumer wrapper would also need to use forwardRef. I updated the sandbox https://codesandbox.io/p/sandbox/falling-rain-vw3cww?file=%2Fsrc%2FMyComponentWrapped.tsx

    The use of static defaultProps is also how React class components do it.

    We're probably not ready to commit to checking for it in the React wrapper generation as it implies a contract with the base custom element class (currently the wrapper isn't tied to LitElement/ReactiveElement though we could decide to change that), let alone it would have no meaning for standalone LitElements as is. If/when we add support for default property values in LitElement, it likely would involve the property option, rather than a separate defaultProp block like that.

    I'm curious if you have direct, non-React wrapped, consumers of the custom elements too for your project and if they want this default property behavior as well?

  8. moved this to 📋 Triaged in Lit Project Boardon Sep 28, 2023
  9. changed the title [-][labs/react] Lit Element in React Component Doesn't Apply Default Prop Value on Re-render without Property Set[/-] [+][react] Lit Element in React Component Doesn't Apply Default Prop Value on Re-render without Property Set[/+] on Jan 16, 2024
  10. rivajunior commented on May 17, 2024

    @rivajunior
    ContributorAuthor

    Hey @augustjk I am sorry about the delay. I forgot about this issue.

    I'm curious if you have direct, non-React wrapped, consumers of the custom elements too for your project and if they want this default property behavior as well?

    We don't have non-React wrapped consumers, but I believe we would like this behavior as well. At least for me, it makes sense.

    I created a new codesandbox https://codesandbox.io/p/devbox/jovial-silence-xph9nk with the updated packages and it looks like everything is good now. Thank you for fixing the issue.

    I only had to add the following code to have the "default props" behavior

      protected override willUpdate(
        _changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>,
      ): void {
        super.willUpdate(_changedProperties);
    
        if (_changedProperties.has("someText") && this.someText === undefined) {
          this.someText = defaultProps.someText;
        }
    
        if (_changedProperties.has("someNumber") && this.someNumber === undefined) {
          this.someNumber = defaultProps.someNumber;
        }
    
        if (
          _changedProperties.has("someBoolean") &&
          this.someBoolean === undefined
        ) {
          this.someBoolean = defaultProps.someBoolean;
        }
      }

    This is a workaround I would like to have an API to do this for me.

  11. moved this from 📋 Triaged to ✅ Done in Lit Project Boardon May 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions