eveo
eveo

Reputation: 2833

How do you set displayName dynamically with a higher order component?

I'm trying to set displayName dynamically because every component renders as <Component ... /> and makes it impossible to debug. I've so far set static displayName on each component and it works fine, it's just a lot of repeated code.

Many components extend this component and as such result's in a hierarchy entirely of unnamed components. How could I save setting static displayName on each component that extends Component?

root component

export class Component extends React.Component {
  static component = 'span';
  static style = {
    base: {}
  };

  constructor() {
    super(...arguments);
    this.style = this.constructor.style;
    this.switches = this.constructor.switches;
    this.component = this.constructor.component;
    // this.displayName = this.constructor.displayName;
  }

  getRenderProps() {
    ...
    return props;
  }

  render() {
    return React.createElement(this.component, this.getRenderProps(), this.props.children);
  }
}

other classes

class SomeClass extends Component {
   ...
}

SomeClass now renders as <Component> unless explicitly setting static displayName on it resulting in:

enter image description here

Upvotes: 2

Views: 1551

Answers (1)

Eran Or
Eran Or

Reputation: 1532

const decorate = <P extends object>(
    Component: React.ComponentType<P>,
    displayName?:string
  ): React.FC<P> => ({
      ...props
  }: P) =>{
      const WithName = withStyles({})(Component as React.FC) 
      WithName.displayName = displayName
    return <WithName {...props as P} />
  }

And then use like this:

(Note! need to be outside a component)

const MyComp = decorate(Compo, "MyComp")

If someone found a cleaner way tag my name please

Upvotes: 3

Related Questions