React: Prevent auto-refresh when a class's state change

Viewed 3241

I am new to react.

I have a class-based component. Let's say the code inside is:

state = {message: "Hello"}

render(){
<div>  
   <p>this.state.message</p>
   <button onclick={() =>this.setState({message: "World"})}>click here</button>
</div>
}

When I click the button, display on the screen change from "Hello" to "World", but then the page refresh and the display turns back to the default "Hello" again.

How should I prevent the automatic refresh? I want my page to display "World" after I press the button.

I really appreciate your help.

2 Answers

A <button> element's default behavior is to submit the page (or form that it's in), which triggers a refresh.

To avoid this, set its type to button:

<button type="button" onclick={() =>this.setState({message: "World"})}>click here</button>

You should add the button type to the control, as by default this is set to submit, which causes the page to refresh.

<button type="button" onclick={() =>this.setState({message: "World"})}>click here</button>

https://www.w3schools.com/tags/att_button_type.asp

Related