0
votes

I have problem with rather simple task. On button click I want to console log inputs value. What happens is that it logs on input change and not on click. What am I doing wrong?

   var Tasker = React.createClass({
          getInitialState: function() {
            return {
            };
        },
        handleChange: function(event) {
            this.setState({
                value: event.target.value
            });
        },
        render: function () {
          return (
            <div>
              <input type="text" value={this.state.value} onChange={this.handleChange}/>
              <button onClick={this.props.onClick(this.state.value)}>Add task</button>
          </div>
          );
      }
  });

   var List = React.createClass({
        handleNewTaskClick: function (value) {
          console.log(value);
      },
      render: function  () {
        return (
            <Tasker onClick={this.handleNewTaskClick}/>
            );
    }
});
      ReactDOM.render(<List />, document.getElementById('react-app'));

JSbin link:https://jsbin.com/vororomuzo/edit?html,console,output

1

1 Answers

0
votes

Not sure why the onClick is fired every time the state is changed as opposed to when the event is fired, but if you create a handleClick method and call it instead of handling it in the jsx it works correctly.

handleClick: function() {
  this.props.onClick(this.state.value);
},
render: function () {
  return (
    <div>
      <input 
        type="text" 
        value={this.state.value} 
        onChange{this.handleChange}
      />
      <button onClick={this.handleClick}>Add task</button>
    </div>
  );
}

Updated jsbin