Search code examples
reactjsresizestatepage-refresh

ReactJS: How to stop screen from refreshing State when window is resized?


Our React site has several component/pages that are basically CRUD processing: Collect several fields from the user, and on Submit store those fields as a database record. Today's issue is that a user can fill out several fields, getting those values stored in State, and then lose everything if they resize the screen for any reason. Apparently, "resize" automatically includes "refresh".

We want the new CSS to take effect (media-query for mobile vs desktop, for instance). But we don't want all our values in State to be cleared out, and the screen reset to the beginning.

Is it possible to get what we want?

A typical field is

  <TextInput
             className={"required"}
             id="firstName"
             name="firstName"
             value={this.state.firstName}
             onChange={this.handleChange}
             placeholder="First Name"
             labelText="First Name"
             invalid={this.state.firstNameInvalid}
             invalidText="First Name is required"

The handleChange to put the input value into State is:

handleChange(event) {
        const {name, value} = event.target
        this.setState({[name]: value})
    }

Values in State work fine, until the window size is changed in any way: maximize/minimize/drag, turn a mobile device from vertical to horizontal, etc. In that case, it behaves as if you had done a manual browser refresh: All State goes back to initial values.

One clue we're considering is that we are using the react-sidenav library along with react-router. Would either of those cause something like this?


Solution

  • FYI, we found the culprit. In our wrapping nav.js, using react-sidenav, there was an on-resize handler that set the size into State. By setting State, the sidenav re-rendered. When that re-rendered, the react-router nested within it also re-rendered, essentially causing the page refresh.