4

I wanted to use spread operator to set the component props. This is mainly because I don't want to use state for each of the props value. Is this possible? The code below returns an error saying that the props are missing. Thanks in advance!

const compProps = { 
    label: 'Test Label',
    value: 'Test Value',
    icon: 'test-icon'
}

<CustomComp {...compProps} />

Update:

I'm using TS on react, as strongly typed language, it doesn't allow me to have an undefined props as initial value. I managed to fix this by checking the props first.

{ compProps && 
    <CustomComp {...compProps} /> }
Wreeecks
  • 2,186
  • 1
  • 33
  • 53

2 Answers2

2

Yes, we can do that, But you need to use spread operator inside braces.

 const compProps = { 
   label: 'Test Label',
   value: 'Test Value',
   icon: 'test-icon'
 }

 <CustomComp {...compProps} />

In Child component you can access props like this props.label

Abhilash CR
  • 184
  • 1
  • 4
1

Yes. You can use as below.

const compProps = { 
  label: 'Test Label',
  value: 'Test Value',
  icon: 'test-icon'
}

<CustomComp {...compProps} />
Ganesan C
  • 269
  • 1
  • 3
  • 9
  • Actually this is what I did. It turns out TS is strict on initial value, so what need to do is check the props first, make sure that it's not undefined before showing the component. – Wreeecks Oct 06 '21 at 04:54
  • Check this sand box link https://codesandbox.io/s/red-cache-8m7hg?file=/src/App.tsx. We can mention types for props we receive in component and using defaultProps in react we can mention initial value to props. – Abhilash CR Oct 07 '21 at 14:35