-1

I'm trying to specify default values for optional props for a React component.

I can do this, and the I can get the value of the optional property 'y' correctly.

interface CompProps {
  x: number;
  y?: number;
}

const compPropsDefault: CompProps = {
  x: 100,
  y: 200
}

function CompA({ x, y = compPropsDefault.y }: CompProps = compPropsDefault) {
  const props = {x, y};
  console.log(props);
}

CompA({ x: 100 })

// Outputs: {"x": 100, "y": 200}

But I need to do { x, y = compPropsDefault.y } kind of destructuring all the time, which gets cumbersome with larger objects. Also, ideally I'd want to keep all input props in a props object.

This works, but I couldn't find any docs/examples recommending this. Would it be bad practice to do this instead? Or is there a better way to get the desired result?

function CompB(props: CompProps = compPropsDefault) {
  props = { ...props, ...compPropsDefault };
  console.log(props);
}
jetxs
  • 5
  • 3
  • Why do you want `CompA({})` and `CompA()` result in different `x` values? – Bergi Apr 03 '23 at 19:39
  • Ah, just realizing that it will result in different values for `x`. I wasn't considering the possibility that CompA({}) could be called. – jetxs Apr 04 '23 at 02:54

1 Answers1

0

That's a reassignment, not an override. Reassignment is almost always an anti-pattern in React, which follows the principles and philosophies of functional style.

default props object

interface CompProps {
  x: number;
  y?: number;
}

const defaultProps: CompProps = {
  // x: 100  // you will never see this because CompA requires `x`
  y: 200
}

function CompA(props: CompProps) {
  const { x, y } = {...defaultProps, ...props} // 
  return [ x, y ]
}

CompA({ x: 100 })
// ✅ [ 100, 200 ]

CompA({ x: 300, y: 600 })
// ✅ [ 300, 600 ]

CompA({ y: 999 })
// ✅ Error: Property "x" is missing

destructured defaults

interface CompProps {
  x: number;
  y?: number;
}

function CompA({ x, y = 5 }: CompProps) {
  return [ x, y ]
}

CompA({ x: 100 })
// ✅ [ 100, 200 ]

CompA({ x: 300, y: 600 })
// ✅ [ 300, 600 ]

CompA({ y: 999 })
// ✅ Error: Property "x" is missing
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • You're right what I was doing is flawed.. I hadn't considered `CompA({ y: 999 })`. Will just use destructuring as recommended by the docs. – jetxs Apr 04 '23 at 03:00
  • I mean to suggest both approaches as valid. `CompA({ y: 999 })` gives an error which is good because `x` is required as per `CompProps`. – Mulan Apr 04 '23 at 13:35