Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a page (state) in a react app

I'm beginning to learn react.js and I've developer a simple rock paper scissors game in a react app. I'm finding it a bit difficult creating a reload button because it is of course different from the javascript button with a function like:

<button onclick="reload">RESTART GAME</button>
function reload() {
  location.reload();
}

For this react app what I thought would work was:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
function refreshPage(){ 
  window.location.reload(); 
}

to the App.js file but I'm getting the error message:

./src/App.js
Syntax error: Unexpected token (64:11)

  62 |   }
  63 | 
> 64 |   function refreshPage(){
     |            ^
  65 |     window.location.reload();
  66 |   }
  67 | } 

The complete project can be found here github (npm start will launch the project in terminal/console)

Any insight into how to correct this would be much appreciated, thank you!

like image 397
T.Doe Avatar asked Oct 07 '17 07:10

T.Doe


2 Answers

Check the code snippet below for workaround for the refreshing page in order to reset the game.

But this is not the best practice since React support changing the state which makes (by default) the component re-render. React has the concept called Virtual DOM. so that the app will be pretty fast. Because React will update the actual DOM by comparing diff.

It is best to change the state as other answers suggested. this.setState({games:[]})

Below is the code snippet for workaround(refreshing page)

class App extends React.Component {
    render() {
      return ( < button onClick = {this._refreshPage} > test </button>);
      }

      _refreshPage() {
        console.log("Clicked");
        window.location.reload();
      }
    }


ReactDOM.render( < App / > , document.getElementById('app'));
<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="app"></div>
like image 168
dwij Avatar answered Sep 30 '22 17:09

dwij


In react you don't have to refresh page to reset state. I looked at your project and saw that you are holding your scores and game data in component's state. This helps you to reset game easily with just setting the state to the initial values.

For Example

// add a method to your component for resetting state
restartGame(event) {
  this.setState({ games: [] });
}

// and in your components render or any other place add the reset button
<button type="button" onClick={ this.restartGame.bind(this) }>
  <span>Reload</span>
</button>

Don't forget to bind your methods to be able to use this in them. For more information about that you can read react documentation for Handling Events.

like image 36
bennygenel Avatar answered Sep 30 '22 17:09

bennygenel