Digipng Digipng - 1 month ago 14
React JSX Question

Button onClick does not working in reactjs

I'm new to reactjs. I called this libraries in head tag:

<script src="react/build/react.js"></script>
<script src="react/build/react-dom.js"></script>
<script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/15.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<script src="chat-component.js" type="text/babel"></script>


and this is my react code:

var ChatApp = React.createClass({
getInitialState: function () {
return {
messages: [],
socket: window.io('http://localhost:3000')
}
},
componentDidMount: function () {
var self = this;
this.state.socket.on("receive-message", function (msg) {
console.log(msg);
self.setState({messages: self.state.messages.push(msg)})
});
},
render: function () {

return (

<div>
<input id="message" type="text"/>
<button type="button" onClick={this.submitMessage} id="demo" value="send">send</button>
</div>
)
},
submitMessage: function () {

var message = $('#message').value;
// this.socket.emit("new-message", message);
console.log(message);
},

});

ReactDOM.render(
<ChatApp />,
document.getElementById("chat")
);


Why Button onClick does not working in my code? also in inspector, onClick does not exist :

<button type="button" id="demo" value="send">send</button>


I know my question is repeated but I really don't find its solution.

Answer

Place the submitMessage function above render.

When render executes, this.submitMessage should be defined. In your code, it is defined only after render. So, It won't be called. And use val() to get the value from the textbox using jQuery

var ChatApp = React.createClass({
  getInitialState: function () {
    return {
        messages: [],
    }
  },
  submitMessage: function () {

    var message = $('#message').val();
    // this.socket.emit("new-message", message);
     console.log(message);    
  },
  render: function () {

      return (

          <div>
              <input id="message" type="text"/>
              <button type="button"  onClick={this.submitMessage} id="demo" value="send">send</button>
          </div>
      )
  }
});

ReactDOM.render(
<ChatApp />,
document.getElementById("chat")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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="chat"></div>