2

I have a higher order component that is used in a few different components. I'd like to be able to alter behaviour based on the component passed to the HOC:

const Field = Component => {
  return class WrappedField extends React.Component {
    const type = Component.name === 'EmailField' ? 'email' : 'text'
    render() {
      return <Component type={type} />
    }
  }
}

// Then used like so:

const TextField = props => <input />

export default Field(TextField)

This works in dev, but in production Component names are minified, so this fails. I have a few posts on the topic, like this one which suggests using React internals, or this one which suggests reading from the constructor, which does not seem to work.

The only workaround I have found is to do pass a second argument:

export default Field(TextField, 'TextField')

Which obviously does not get minified in production, but it seems crazy that the name cannot be dynamically read or saved.

Any suggestions for how to dynamically derive the component name in an HOC greatly appreciated.

Toby
  • 12,743
  • 8
  • 43
  • 75

1 Answers1

1

Another way is to compare the components directly, like this :

const TextField = props => <input {...props} />;
const EmailField = props => <input {...props} />;

const Field = Component => {
  return class WrappedField extends React.Component {
    render() {
      const type = Component === EmailField ? 'email' : 'text'
      return <Component type={type} />;
    }
  };
};

export default Field(TextField)
Mohamed Ramrami
  • 12,026
  • 4
  • 33
  • 49
  • This would be awesome if it works - I've tried a few methods to test it out, but the problem I'm running into is that when I try to do the comparison I end up in a loop, because the components are all exported/imported, so the HOC is trying to compare to itself. Do you see a workaround to that without storing everything in a single file? – Toby Feb 09 '19 at 17:26
  • I don't think I understand. Are you importing the HOC in TextField also ? I have a working example here https://codesandbox.io/s/qlmrx14914 – Mohamed Ramrami Feb 09 '19 at 17:35
  • Ah, I see - the problem I was having is that I declare my fields then default export them wrapped with the HOC, so if I try to compare them in the HOC they're already wrapped. Your approach with separating the fields from the wrapped versions of the fields will work for me - many thanks! – Toby Feb 09 '19 at 17:48
  • Glad it helped. – Mohamed Ramrami Feb 09 '19 at 17:50