mayooran mayooran - 11 months ago 64
Javascript Question

Passing react text field input values as parameters to a method

I have the below input fields of which I need to get the entered inputs and pass it to the onClick event of the button shown below.

<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/>
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/>
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/>

I have a method called publish which takes two string arguments. In place of those strings, I need to pass the values entered in the input fields. How can I achieve this without storing the values in states? I do not want to store the input field values in state variables. Any help would be much appreciated.

Answer Source

In this case you can use states, like so

class App extends React.Component {
  constructor() {
    this.state = {
      topicBox: null,
      payloadBox: null
    this.publish = this.publish.bind(this);
    this.handleChange = this.handleChange.bind(this);
  handleChange({ target }) {
      []: target.value

  publish() {
    console.log( this.state.topicBox, this.state.payloadBox );
  render() {
    return <div>
        placeholder="Enter topic here..." 
        value={ this.state.topicBox }
        onChange={ this.handleChange } 
        placeholder="Enter payload here..."
        value={ this.state.payloadBox } 
        onChange={ this.handleChange } 
      <button value="Send" onClick={ this.publish }>Publish</button>

ReactDOM.render(<App />, document.getElementById('container'));
<script src=""></script>
<script src=""></script>
<div id="container"></div>