Reputation: 111
import React from 'react'
export default (props) => (
<div {...props}>
<svg focusable="false" fill="white" viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"></path>
</svg>
</div>
)
In the above code we are passing props inside the div element. Let's not worry about the svg tag, but how the code is working from React perspective?
Upvotes: 3
Views: 1120
Reputation:
It(...
) is called spread attribute which is used to make passing of multiple props easy.
For example if you have any component having 3 states/values and you want to pass them as props to other component , sounds easy but it become much untidy if you have 100 props to pass.
<MyComponent one={} two={} three={} .... upto 100 props />
Hence instead of pasing 100 props, you can wrap them into an object and use this spread notation.
MyObject = { one:1, two:2, three:3, ....., hundred:100 };
<MyComponent {...props} />
And here in this case if you open MyComponent, to extract all the props , you can do like this
import React from 'react'
const MyComponent = (props) => (
return(
<div {...props}>
.
.
.
</div>
}
)
Upvotes: 1
Reputation: 923
In the above code you are exporting an anonymous react functional component.
So whenever you call that component suppose you call it by name <MyIcon />
and whenever you pass any prop to that component it will get forwarded to div
by using {...props}
(We can use spread operator ...
on props because props is nothing but an object).
...
<MyIcon style={{ backgroundColor:"red" }} className="myIcon" id="icon"/>
...
The above code will pass style
, className
, and id
props to div
.
In short whatever props you pass to MyIcon
will be passes to the div
.
Upvotes: 2
Reputation: 15520
{...props}
means we will pass all props/attributes to that element. For example, you have a few props like below
const { width, height, isOn, isRed } = props
If you want to pass all these props, the manual way can be
<div width={width} height={height} isOn={isOn} isRed={isRed}></div>
It's still good, but what if you have like 10 more props needing to pass?
The simple way can be
<div {...props}></div>
All props inside props
will be passing automatically
You can check the full document here for better understanding
Upvotes: 2
Reputation: 27245
It's passing the props given to the component down to the div using spread syntax.
This would allow a user of the exported component to pass props in to be rendered on the div, like style, className, event handlers, etc., without the component needing to know or care what those props are.
Upvotes: 1