Home > Mobile >  Is it possible to use spread out operator to set the react component props?
Is it possible to use spread out operator to set the react component props?

Time:10-06

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} /> }

CodePudding user response:

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

CodePudding user response:

Yes. You can use as below.

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

<CustomComp {...compProps} />

CodePudding user response:

you can try like this

const compProps = { 
label: 'Test Label',
value: 'Test Value',
icon: 'test-icon', 
}
<CustomComp {...compProps} />
  • Related