Reputation: 734
I want to provide a form that allows the user to change the size of an element. But since the element rendering is quite heavy, I do not want to use onChange here so it triggers rerendering of the whole thing each keystroke. How do I make my form only acting on submit?
The following code complains that I need an onChange event on each input field. But when would that not cause the app to rerender each time I change the input?
const App = (props) => {
//const [zoom, setZoom] = useState(1);
const [height, setHeight] = useState(props.height);
const [width, setWidth] = useState(props.width);
const handleResize = (e) => {
const value = e.target.value;
setWidth(value.width);
setHeight(value.height);
e.preventDefault();
}
return (
<>
<div>
<form onSubmit={handleResize}>
<input type="text" value={width} name="width" />
<input type="text" value={height} name="height" />
<input type="submit" value="OK" />
</form>
</div>
<div className="workspace">
<Workspace width={width} height={height} />
</div>
</>
);
}
Upvotes: 0
Views: 2010
Reputation: 921
Use uncontrolled inputs and read their value in the handleResize
function.
To make the inputs uncontrolled pass defaultValue
instead of value
.
Like so:
const widthRef = useRef();
const heightRef = useRef();
const handleResize = (e) => {
const newWidth = widthRef.current.value;
const newHeight = heightRef.current.value;
setWidth(newWidth);
setHeight(newHeight);
e.preventDefault();
};
A working example: https://codesandbox.io/s/nice-ishizaka-xewyq?file=/src/App.js
Upvotes: 1
Reputation: 968
What are you looking for is called Uncontrolled Components.
Take a look here: https://reactjs.org/docs/uncontrolled-components.html
Upvotes: 1
Reputation: 41893
Remove the value
prop from inputs to keep it uncontrolled. You can get the input values directly from the form:
const handleResize = (e) => {
e.preventDefault();
const [width, height] = e.target.children;
const w = width.value;
const h = height.value;
}
Upvotes: 1
Reputation: 667
Form won't re-render on onChange unless you update state inside onChange. If you don't intend to do anything onChange then simply do this onChange ={()=>{}}
Upvotes: 1