0

I wonder if it is a better way to DRY this code, have you guys any ideas? The props are the same, just the component change...

render() {
    const { input: { value, onChange }, callback, async, ...rest } = this.props;

    if (async) {
      return (
        <Select.Async
          onChange={(val) => {
            onChange(val);
            callback(val);
          }}
          value={value}
          {...rest}
        />
      );
    }

    return (
      <Select
        onChange={(val) => {
          onChange(val);
          callback(val);
        }}
        value={value}
        {...rest}
      />
    );
  }
Patrick Ferreira
  • 1,983
  • 1
  • 15
  • 31
  • 5
    If the code is working and you want to improve it/get it reviewed, you can post it on [codereview.se]. Before you do, please have a look at [How do I ask a good question?](http://codereview.stackexchange.com/help/how-to-ask) – Tushar Jan 04 '17 at 14:10
  • Possible duplicate of [React / JSX Dynamic Component Name](http://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name) – Whymarrh Jan 04 '17 at 14:12
  • @Tushar thanks, I'll remember it next time. – Patrick Ferreira Jan 04 '17 at 14:16

1 Answers1

1

With:

let createElement = function(Component) {
    return (
        <Component onChange={(val) => { 
            onChange(val);
            callback(val);
            }}
            value={value}
        {...rest}
      />
    );
};

you can do

let selectAsync = createElement(Select.Async);
let select = createElement(Select);

You can render them in the jsx part with {{select}} and {{selectAsync}}

P.S.: I didnt test this directly, but did something very similar a few days ago, so this approach should work. Note that Component must start with a capital letter.

René Jahn
  • 1,155
  • 1
  • 10
  • 27