Created
February 21, 2015 22:13
-
-
Save sausman/5e0052fb6885977c50dd to your computer and use it in GitHub Desktop.
CyaSS React Component - mimic :hover and :active with inline styles
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
import React from "react/addons"; | |
import m from "./m"; | |
// https://www.youtube.com/watch?v=GOiVYbWJDOA | |
export default class CyaSS extends React.Component { | |
constructor() { | |
super(); | |
this.state = { | |
hover: false, | |
active: false | |
}; | |
} | |
_onHover(hover) { | |
this.setState({ | |
hover: hover, | |
active: this.state.active && hover | |
}); | |
} | |
_onActive(active) { | |
this.setState({active: active}); | |
} | |
_modifyStyle(style) { | |
style = m(style, | |
this.state.hover && style.hover, | |
this.state.active && style.active); | |
style.hover = undefined; | |
style.active = undefined; | |
return style; | |
} | |
_modifyChild(child) { | |
return React.addons.cloneWithProps(child, { | |
onMouseOver: this._onHover.bind(this, true), | |
onMouseOut: this._onHover.bind(this, false), | |
onMouseDown: this._onActive.bind(this, true), | |
onMouseUp: this._onActive.bind(this, false), | |
hover: this.state.hover, | |
active: this.state.active, | |
style: this._modifyStyle(child.props.style) | |
}); | |
} | |
render() { | |
let child = React.Children.only(this.props.children); | |
return this._modifyChild.call(this, child); | |
} | |
} |
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
import React from "react"; | |
import CyaSS from "./CyaSS"; | |
let linkStyle = { | |
color: 'blue', | |
hover: {color: 'green'}, | |
active: {color: 'red'} | |
}; | |
React.render(( | |
<CyaSS> | |
<a href="#" style={linkStyle}>Link</a> | |
</CyaSS> | |
), document.body); |
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
import objectAssign from "object-assign"; | |
export default function m() { | |
var res = {}; | |
for (let i in arguments) { | |
if (arguments[i]) objectAssign(res, arguments[i]); | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment