Reputation: 2274
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} /> }
Upvotes: 4
Views: 1272
Reputation: 277
Yes. You can use as below.
const compProps = {
label: 'Test Label',
value: 'Test Value',
icon: 'test-icon'
}
<CustomComp {...compProps} />
Upvotes: 1
Reputation: 194
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
Upvotes: 2