Ycon Ycon - 1 month ago 9
React JSX Question

Pass single value within onClick (without using a form submit)

Rather than creating several putPriority fetches, I'd ideally just like to pass a singular value.

But this value won't be entered via the user (ie not an input field)

I'd like pass this value through an onClick.

In my example, I'd like the onClick to pass a single number to "status" in the fetch (this.state.level).

Basically I want it to work like this:

putPriority: function(e) {
e.preventDefault();
return fetch(DATA_API, {
method: 'PUT',
body: JSON.stringify({
status:this.state.level,
tag:[
{}
]
})
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
},


...

render: function(){
return (
<Button onClick={this.putPriority} title="level" value="1">High </Button>

<Button onClick={this.putPriority} title="level" value="2">Medium </Button>

<Button onClick={this.putPriority} title="level" value="3">Low </Button>
}
)};

Answer

You can use bind() to pass value to the handleClick function and the instead of this.state.level just use value liek

body: JSON.stringify({
     status:value,
     tag:[
       {}
      ]
  })

var App = React.createClass ({
putPriority: function(value, e) {
    e.preventDefault();
    console.log(value);
  },

  render: function(){
        return (
          <div>
    <button onClick={this.putPriority.bind(this, '1')} title="level" value="1">High </button>

    <button onClick={this.putPriority.bind(this, "2")} title="level" value="2">Medium </button>

    <button onClick={this.putPriority.bind(this, "3")} title="level" value="3">Low </button>
</div>  
)  
}
  
})
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>