Resetting default values for controls in React

Viewed 1234

I have a React application which consists of a main 'canvas' component, into which 3rd-party SVG is rendered, and a toolbar component which is used to control zooming and various other operations on the canvas. The user can change the contents of the canvas using a dropdown, and when this happens the controls (zooming, etc) should reset to their defaults.

The main application container, the canvas and the toolbar are all class components, with lifecycle management. The controls on the toolbar are all stateless functional components. Originally this was a Backbone app, and changing the canvas meant destroying the view containing the canvas and controls and creating a new one, with default values. I am struggling to achieve the same thing so easily with React, however. My zoom control is a simple functional component which renders a select control with options for various zoom percentages:

function zoomPcntControl(props) {
  const zoomLevels = [10, 25, 50, 75, 100, 125, 150, 200, 400, 800, 1600, 2400, 3200];
  const options = zoomLevels.map((level, key) => {
    return (
      <option key={key}> {level+"%"} </option>
    );
  });
  render() {
    return (
      <div>
        <select id="zoom-list" defaultValue="100%" autoComplete="off" onChange={props.handleZoomPcnt}>
          {options}
        </select>
      </div>
    )
  }
}

What I want to ensure is that the displayed value of the control is reset to the default value of 100 each time the canvas component is redrawn. Short of resorting to jQuery how can I achieve this? I know about the key trick, but that seems like a crude solution - I tried it, and the visual results were not satisfactory either.

The default value can't really be modelled as state, as it's a fixed value for the app. And in any case the zoom control is a functional component, with no state of its own. The only change in its 'state' is as a result of user interaction.

1 Answers

There are two ways to do it in React.

Make the Zoom component a controlled component. Pass the zoom value as props and use value instead of defaultValue.

<select value={props.value} onChange={props.handleZoomPct} />

Use ref on Zoom component. When the defaultValue needs to be reset, use the ref to reset the value.

reset() {
  this.selectRef.current.value = '100%';
}
Related