Skip to content

Instantly share code, notes, and snippets.

@vjeux
Created July 31, 2016 02:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vjeux/8e27dd06c64dc566bfee705e1b19cb18 to your computer and use it in GitHub Desktop.
Save vjeux/8e27dd06c64dc566bfee705e1b19cb18 to your computer and use it in GitHub Desktop.
// Solution #1: Generic Override (like CSS)
var ButtonGroup = React.createClass({
render() {
return <div>{this.props.buttons.map((btn, i) =>
<Button style={{
...(i !== 0 && {marginLeft: 0})
...(i !== this.props.buttons.length - 1 && {marginRight: 0})
}} />
)}</div>;
}
});
var Button = React.createClass({
render() {
return <div style={{
...styles.button,
...this.props.style,
}} />;
}
});
// Solution #2: Encapsulated behavior
var ButtonGroup = React.createClass({
render() {
return <div>{this.props.buttons.map((btn, i) =>
<Button
hasLeftSibling={i !== 0}
hasRightSibling={i !== this.props.buttons.length - 1}
/>
)}</div>;
}
});
var Button = React.createClass({
render() {
return <div style={{
...styles.button,
...(hasLeftSibling && {marginLeft: 0}),
...(hasRightSibling && {marginRight: 0}),
}} />;
}
});
@threepointone
Copy link

here's a take on the above with glamor -

let addToButtStyle = merge(
  not(':first-child', { margin:0 }), 
  lastChild({ marginRight: 10 })
)

class ButtonGroup extends React.Component {
  render() {
    return <div>
    {this.props.labels.map(label => 
      <Button style={addToButtStyle}>{label}</Button>)}
    </div>
  }
}


let defaultStyle = {
  marginLeft: 10,
  display: 'inline',
  border: '1px solid black'
}
class Button extends React.Component {
  render() {
    return <div {...merge(defaultStyle, this.props.style)}>{this.props.children}</div>  
  }  
}


// alternately, with context 
@btnmerge(merge(  // assume this decorator magically comes from button.js 
  not(':first-child', { margin:0 }), 
  lastChild({ marginRight: 10 })
))
class ButtonGroup extends React.Component {
  render() {
    return <div>
    {this.props.labels.map(label => 
      <Button>{label}</Button>) // no props!
  }
    </div>
  }
}


// button.js 
let defaultStyle = {
  marginLeft: 10,
  display: 'inline',
  border: '1px solid black'
}
class Button extends React.Component {
  static contextTypes = {
    // yada yada 
  }
  render() {
    return <div {...merge(defaultStyle, this.context.buttStyle)}>{this.props.children}</div>  
  }  
}

@taion
Copy link

taion commented Jul 31, 2016

Trying to move discussion to styled-components/spec#5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment