Created
October 23, 2018 11:27
-
-
Save valex/680cb5e190c2ded4195dc222e9e326fe to your computer and use it in GitHub Desktop.
Attrs spread
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>JSX spread</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<div id="app"> | |
<!-- my app renders here --> | |
</div> | |
<script charset="utf-8" crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> | |
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> | |
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> | |
<script type="text/babel"> | |
class FancyLink extends React.Component{ | |
render() { | |
/* | |
var attr = { | |
href: 'http://example.org', | |
target: '_blank', | |
}; | |
// return <a {...attr}>Hello</a>; | |
return ( | |
<a | |
href={attr.href} | |
target={attr.target}> | |
Hello | |
</a> | |
); | |
*/ | |
/* | |
switch(this.props.size) { | |
// do something based on the `size` prop | |
} | |
var attribs = Object.assign({}, this.props); // shallow clone | |
delete attribs.size; | |
*/ | |
var {size, ...attribs} = this.props; | |
console.log(size); // medium | |
console.log(attribs); // {href: "http://example.org", style: {color: "red"}, target: "_blank", children: "Hello"} | |
switch(size) { | |
// do something based on the `size` prop | |
} | |
return <a {...attribs}>{this.props.children}</a>; | |
} | |
} | |
ReactDOM.render( | |
<div> | |
<FancyLink | |
href="http://example.org" | |
style={{color: "red"}} | |
target="_blank" | |
size="medium"> | |
Hello | |
</FancyLink> | |
</div>, | |
document.getElementById('app') | |
); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment