When you run the application, index.html is loaded as the first page. On this page there is a script , the functions of which are hung by pressing the menu buttons and:

 <script type="text/javascript" src="./app/Login.js"></script> 

The Login.js file Login.js React.Component Login . This component has a button, when clicked, the following code is executed:

 ReactDOM.render( <Verification />, document.getElementById('container') ); 

This code replaces the Login component with the Verification component, whose render function is below:

 render() { return ( <div id="divLoginPanel"> <form id="formLoginPanel"> <div className="divLoginPanel_Header"> Verification </div> <div className="divLoginPanel_Container"> Тут не важные для вопроса вещи <p> <button className="loginConfirmButton" onClick={this.handleConfirmClicked}>Confirm</button> <button className="loginCancelButton" onClick={this.handleCancelClicked}>Cancel</button> </p> </div> </form> </div> ); } 

Here are the functions hung on the buttons:

 handleConfirmClicked() { console.log("In handleConfirmClicked"); } handleCancelClicked() { console.log("In handleCancelClicked"); /* ReactDOM.render( <Login/>, document.getElementById("container") ); */ } 

Well, and my problem: when you click on any of the buttons Confirm and Cancel, everything is loaded again. That is, not just the Verification component, but the whole html, while the Login component is displayed. It also clears the console and re-displays what is displayed at the very beginning.

What's wrong?

  • 2
    Instead of changing the Login to Verification via ReactDOM.render, you should use the conditional operator where you render the main tree. - Pavel Mayorov
  • And the button must be added to return false in the handler so that they do not reload the page. - Pavel Mayorov

1 answer 1

By default, the html button element has a type attribute with a value of submit. That is why this behavior when pressed. Change the type to button.

 <button type="button" onClick="...">Button</button> 

Or, in the handler for the Event argument, call the preventDefault method

 handleConfirmClicked(e) { e.preventDefault(); console.log("In handleConfirmClicked"); } 

Or, in the handler, at the end execute return false

 handleConfirmClicked() { console.log("In handleConfirmClicked"); return false; }