Markcce Eros Markcce Eros - 29 days ago 10
React JSX Question

React creating a button - non hardcoded properties

I am trying to create a react button and here's the current code:

var React = require('react');

var buttonStyle = {
margin: '10px 10px 10px 0'
};

var Button = React.createClass({
render: function () {
return (
<button
className="btn btn-default"
style={buttonStyle}
onClick={this.props.handleClick}>{this.props.label}</button>
);
}
});

module.exports = Button;


The problem is that I don't want the className hardcoded, no the onclick.

I want to be able to add the classes and onclick event outside this code...for example:

<Button bStyle="myChosenStyles" onclick="myChosenFunction" />


How can I do this?

Answer

You need to correctly pass className or click event handler to the props and then use it in component, e.g.:

var Button = React.createClass({
  render: function () {
    return (
      <button
        className={this.props.bStyle}
        style={buttonStyle}
        onClick={this.props.onclick}>{this.props.label}</button>
    );
  }
});

// use {} when passing myChosenFunction to the props
<Button bStyle="myChosenStyles" onclick={myChosenFunction} label="myLabel" />

You code currently has on click handler handleClick which is property of button component (you can simply change the name to onclick). With single or double quotes you can pass string variables (like label, or className). When you want to pass objects, functions, numbers, etc. you need to surround it with curly braces {}.

Comments