1

I have this function, for example:

const FieldRange = props => (
  <div className={b('field-range', props)}>
    {props.children}
    {!!props.errorFieldName && <Field name={props.errorFieldName}/>}
  </div>
);

Eventually I decide that I want it to be more dry, and rewrite it like that, restructuring argument object into properties:

const FieldRange = ({ children, errorFieldName }) => (
  <div className={b('field-range', props)}>
    {children}
    {!!errorFieldName && <Field name={errorFieldName}/>}
  </div>
);

But, oh no, I still need the original object on the second line! Is there a way to destructure an object, but still leave it available in the function body?

2 Answers2

1

IMO, the best method would be to either leave your original code as is, or declare the variables on the first line of the function:

const FieldRange = props => {
  const { children, errorFieldName } = props;
  return (
    <div className={b('field-range', props)}>
      {props.children}
      {!!errorFieldName && <Field name={errorFieldName}/>}
    </div>
  );
);

There's a really hacky solution that allows you to keep the concise body, which is to use a second parameter, which is not passed to the function, which defaults to destructured props:

const FieldRange = (props, { children, errorFieldName } = props) => {

But that's quite confusing, I wouldn't recommend it.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    I see, that is quite ugly looking. I guess I better leave it as it is. –  Mar 24 '20 at 08:04
1

You could misuse a second parameter for destructuring with a default of props.

const FieldRange = (props, { children, errorFieldName } = props) => (
    <div className={b('field-range', props)}>
        {children}
        {!!errorFieldName && <Field name={errorFieldName}/>}
    </div>
);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392