Created
May 8, 2015 06:12
-
-
Save at0g/6b6df72af556ff46e227 to your computer and use it in GitHub Desktop.
react components with rest/spread props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var React = require('react'); | |
var ComponentNoChildren = React.createClass({ | |
getDefaultProps: function () { | |
return { | |
Component: 'div', | |
className: 'component-no-children' | |
} | |
}, | |
render: function () { | |
// Create local variables for Component. | |
// All additional props get created in an object addressable using the rest variable. | |
// This allows additional props to be set on the component, such as { role: 'presentation' } | |
// without the component knowing about them ahead of time. | |
var { Component, ...rest } = this.props | |
// Create the components element: | |
// by default a <div> is created, but this.props.Component could be set to any valid node | |
// such as a 'section' or another react component. | |
// The {...} part is a destructering operation - it returns each key:value from the rest object. | |
// In the case of the default props, it's equivalent to writing className={rest.className} | |
return <Component {...rest} />; | |
} | |
}); | |
module.exports = ComponentNoChildren; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var React = require('react'); | |
var ComponentWithChildren = React.createClass({ | |
getDefaultProps: function () { | |
return { | |
Component: 'div', | |
className: 'component-with-children' | |
} | |
}, | |
render: function () { | |
var { Component, children, ...rest } = this.props; | |
return ( | |
<Component {...rest} > | |
{ children } | |
</Component> | |
); | |
} | |
}); | |
module.exports = ComponentWithChildren; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment