Undisclosed
Undisclosed

Reputation: 1

update input field value in react JS state

this is my first question here,pardon me for any mistake. So ,I have a few inputs and for displaying the values of them I used some elements like h1 and div's which are in a seperate component. I want my elements to have some default value, so for that I kept them in state and then I call an onChange function on inputs which will update my elements state. I tried doing it with event.target like nameElement:event.target.value ,it would have worked if i had one input but because I have multiple inputs ,when I change an input field it gets overwritten by the one I change next. So how can I update only the input field I change. Like if I write something in name input field only the element of CV which is holding the name field should change . Here's my code sandbox link https://codesandbox.io/s/cool-glitter-9w2mh?file=/src/App.js

Upvotes: 0

Views: 591

Answers (1)

B.Anup
B.Anup

Reputation: 585

I am not sure, I got the issue right. But I got into the sandbox and below are my observations.

  1. I would advise using Formik if you are dealing with the user-input form. Link - https://formik.org/docs/tutorial
  2. Since you have created a single state that contains default value as well as user input value, any changes made by the user is not saved after clicking on "viewCV" link that re-renders entire component.

Changes Required

  • Have two states : initialData and userDetails.

  • Modify handleChange

    handleChange = (input, e) => { this.setState((prevState) => { return { ...prevState, [input]: e.target.value }; }); };

  • In components such as workExp, education make sure you link handleChange as an arrow function for the "onChange" event.

    <input onChange={(e) => handleChange("job", e)}>Email

  • Modify submit button to render the Resume template with user inputted values.

  • Modify viewCV link which is causing entire parent component re-rendering.

Upvotes: 1

Related Questions