0

I am using material-ui as a UI framework and I am trying to create a view with two buttons that have different values.

  render: function() {

    return 
      <Card>
        <CardMedia overlay={<CardTitle title={this.props.title} />}>
          <img src={this.props.image}/>
        </CardMedia>
        <CardActions>
          <FlatButton onClick={this._handleClick} label="Good"/>
          <FlatButton onClick={this._handleClick} label="Bad"/>
        </CardActions>
      </Card>

Since I am new to react I think that I miss something basic. How can I pass values to FlatButton, can I use the "ref" attribute? My main problem is that I am using a framework. If I had written those components I would just use props, such as "label" and handle the click event from the component itself.

Update: found a solution, but still if feels like an anti-pattern...

      <FlatButton onClick={this._handleClick.bind(this, 1)} label="Good"/>
      <FlatButton onClick={this._handleClick.bind(this, 0)} label="Bad"/>

Appreciate the help...

2 Answers 2

1

You cannot call onClick on <button /> but you can pass a function to its onClick which is defined inside its Class. You will need to communicate your handleClick to its Child component through props

Hope you get it.

class CardActions extends React.Component {
 ...
}

class FlatButton extends React.Component {
    constructor(props) {
      super(props);
    }

    render() {
        return (
            <button onClick={() => this.props.whenClicked() } type="button">
                {this.props.label}
            </button>
        );
    }
}


class Cards extends React.Component {
    constructor(props) {
      super(props);
    }

    handleClick(event) {
        alert('click');
    }

    render: function () {

        return (
            <CardActions>
                <FlatButton whenClicked={(event) => this.handleClick(event)} title="Dropdown" />
            </CardActions >
        );
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

I'd prefere to create two handling functions in the model:

handleGood: function() {},
handleBad: function() {},


<FlatButton onClick={this.handleGood} label="Good"/>
<FlatButton onClick={this.handleBad} label="Bad"/>

1 Comment

If you have duplicated code in these two functions, you can refactor shared code into another function and call it from good/bad handlers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.