score:1
'...' spread operator produces a shallow copy of an object
handlechange(evt, field) {
let form = {...this.state.form}; //object spread notation
form[field] = evt.value;
console.log('change triggered');
this.setstate({ form: form });
}
score:1
when it comes to forms with react, there are two approaches.
1) uncontrolled components, which basically making use of refs and getting values from the dom (please check the official documentation for more details https://reactjs.org/docs/uncontrolled-components.html) or
2) controlled components making use of states and getting/handling values from react states (please check the official documentation for more details https://reactjs.org/docs/forms.html#controlled-components)
with controlled components => react, state is the single source of truth (as official document suggests), that means, you need to provide methods to handle state changes as user provides the input
with uncontrolled components => instead of updating state on every single change, you can get values inside of onsubmit method and handle them before submit. since you won't need to update the state, you won't need additional functions to handle state changes.
for you seeking of better way to handling things and avoid mutations, it actually depends on your use case, but official documentation suggests that
in most cases, we recommend using controlled components to implement forms. in a controlled component, form data is handled by a react component
when it comes to mutating object, indeed mutations is not good, but there are ways to avoid mutations during state changes. as @mhkit already suggested, you can use spread operator to create a new object (shallow copy, that means it only copies the values) or you could use object.assign()
method.
let's say you have the following state
state = {
form: {
email: '',
name: '',
lastname: '',
}
}
when you user provides the email, you basically need to update the email field, in that case in your handlechangeemail() method, what you can do is the following
this.handlechangeemail = (value) => {
this.setstate(({form}) => {
return {
form: {
...form,
email: value
}
})
}
so with this method, what i basically do is, 1) i utilize functional setstate and extracted the current value of form via es6 object destructuring, then i say that, okay my new form object inside of the state, will have all the existing field that former form has, but, the email field will have a new value based on the new input user provided.
by this way, instead of mutating form object, we created a shallow copy of it with some values are exactly the same, but some values are updated. thus we prevent the mutation
score:2
if you don't want to update each character change you can use onblur
event.
onblur={event => { this.handlechange(event, 'name'); }}
so that on leaving the field only you can update the state.
Source: stackoverflow.com
Related Query
- React - Mutating form object for each change . Is that anyway we can do it in a better way
- How can I change the URL for a React app that I'm hosting myself and to which I forward a domain?
- useEffect React Hook: detecting the change of a property for each object in an array
- How do I implement a functional so that you can interact with the form only once for each user?
- How to change the property of each mapped value so that my component can be used more dynamically for each event?
- Where can I add Form Fields so that they can be sent in Request Payload for POST method, I am inside a React App and using Fetches
- How can I change the value of an object in react based on form data input by the user?
- How can I test a change handler for a file-type input in React using Jest/Enzyme?
- React shouldComponentUpdate() is called even when props or state for that component did not change
- How can I change the format for react datepicker days of the week?
- How can I write a unit test for a react component that calls reduxjs's mapStateToProps?
- React tables Calculating Footer sum on page change on Sort on search, how can we achieve that
- Using React hooks, how can I update an object that is being passed to a child via props?
- How can I change the icon in material-ui date picker for React
- How can I create a reusable function that will setState for a variable object property?
- How to render custom elements for each item in an object (Map data structure) in React TS?
- React Context API - can children/consumers request that the provider change a value?
- REACT: How to create a reusable custom hook with functions and effects that can change & react to changes in a host component's data
- Maintain the context data for each child component on React router change
- I am trying to animate an object with css in react and change the animation (timing) dynamically, how can I set the style after animation end?
- Create a modal popUp for each object using react
- Rendering json object name/description for each object in React
- Rendering text boxes using map function for each object in this.state array. how can i handle text in the text area
- Single Dialog for edit - change object on render - React Modal
- Warning: Unexpected ref object provided for input. Use either a ref-setter function or React.createRef(). With React Hook Form
- React: How to change form validation from onSubmit validation for all fields, to onBlur instant validation for each field in the form?
- How can I change the font size for a <h1> in react bootstrap col?
- React Redux - How do I build a form with material-ui that I can add inputs to?
- React having troubles creating a ticking clock that can change time manually
- event.Target value is null for react form using hooks to handle change
More Query from same tag
- calling a function repeatedly in do while loop
- setState not updating state even with callback and handleFunction - ReactJs
- Passing in a param in setState within React
- parsing wordpress api json response in react using .map
- Problems in highlighting a row of a table when one of its cell is hovered, using React hook useState?
- ReactJs setState undefined when using react-autoBind
- Iterating through the firebase database
- React: Each child in an array or iterator should have a unique "key" prop when Mapping custom components
- React - Invalid hook call. Hooks can only be called inside of the body of a function component
- Return initial state after state changes
- How I can show two nav.link while using a conditional operator?
- how to open a dialog in material-ui on button click
- Invalid exhaustive deps in react hooks
- puting component inside return in reactjs
- Property 'token' is missing in type 'PropsWithChildren<WithUrqlProps>' but required in type '{ token: string; }'
- React Navigation: nesting stack and tab navigator
- Importing PNGs/SVGs into React - TS2307: Cannot find module
- Problems saving data passed through Redux when page refreshes or changes
- Why do I have problem rendering this conditional JSX?
- Loop through two array and based on condition change the property value not working
- draft js data flow examples
- array.map from redux won't return data on the first load of react component
- React fetch multiple endpoints of API error TypeError: fetch(...).json is not a function
- how to redirect to another app after login?
- How can I use media query with emotion/styled/macro?
- React-Router: Nested route not rendering component
- conditionally disable an option using react select not work when change option props passed to the Select
- Redux store can not get state from reducer
- How to Draw Polyline on mapmyindia using React?
- React Array to Object conversion