Save Input Fields in React

share link

by Abdul Rawoof A R dot icon Updated: Feb 17, 2023

technology logo
technology logo

Solution Kit Solution Kit  

In React, to obtain the input field value on a button click in React, we must create a state variable to store the input field's value and set an onChange event handler on the input for updating the state variable when the input field value changes. 


To save the value of an input field on a button, click in React, 

  1. For storing the value of the input field, create a state variable. 
  2. Then to update the state variable when the input filed values changes, set an onChange event handler on the input. 
  3. Ona button elelemt set an onClick event handler. 
  4. Finally, access the state variable in the event handler. 


React state can hold any kind of JavaScript value, including objects. But we should not change objects we hold in the React state directly; when we want to update an object, we need to create a new one and then set the state to use that copy. 


Here is an example of how you can save input fields in React: 

Fig : Preview of the output that you will get on running this code from your IDE.

Code

In this solution we're using React library.

export default function App() {
  const dataContainerRef = React.useRef(null);

  const handleSubmission = e => {
    e.preventDefault();
    const inputs = Array.from(dataContainerRef.current.querySelectorAll("input"));
    // if your inputs have unique names:
    const formData = Object.fromEntries(inputs.map(input => [input.name, input.value]));
    // or just get an array of the values:
    const formDataArray = inputs.map(input => input.value);
  };

  return (
    <div className="App">
      <Inner dataContainerRef={ dataContainerRef } />
      <form onSubmit={handleSubmission}>
        <div>Both two values comma separated: </div>
        <button type="submit"> Submit </button>
      </form>
    </div>
  );
}

export default function Inner(props) {
  const { dataContainerRef } = props;

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div
        ref={dataContainerRef}
        className="data-container"
        dangerouslySetInnerHTML={{ __html: data.htmltag }}
      />
    </div>
  );
}

const data = {
    inputNames: ["Hello", "Welcome"],
}

{
    Hello: "",
    Welcome: "",
}

export default function Inner(props) {
  const { formData, setFormData } = props;

  React.useEffect(() => {
    // initialize `formData`
    setFormData(
      Object.fromEntries(data.inputNames.map(inputName => [inputName, ""]))
    );
  }, [setFormData]);

  const inputRows = data.inputNames.map(inputName => (
    <tr key={inputName}>
      <td>{inputName}</td>
      <td>
        <input
          name={inputName}
          value={formData[inputName]}
          onChange={event => {
            event.persist();
            setFormData(prev => ({
              ...prev,
              [event.target.name]: event.target.value
            }));
          }}
        />
      </td>
    </tr>
  ));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      <table>
        <tbody>{inputRows}</tbody>
      </table>
    </div>
  );
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Open the folder in IDE.
  5. Copy the code using "copy" button above and paste it in app.js file and Inner.js file as per in the demo given below.
  6. Import React and Inner.js file in app.js file.
  7. Open the terminal from IDE.
  8. npm start to run the file.


You can also refer this url 'DEMO' for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for 'how to save input fields in react' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Visual Studio Code 1.73.1.
  2. The solution is tested on node v18.12.1 and npm v8.19.2.
  3. React version-18.2.0.


Using this solution, we are able to save input fields in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to save input fields in React.

Dependent Library

reactby facebook

JavaScript doticonstar image 209050 doticonVersion:v18.2.0doticon
License: Permissive (MIT)

The library for web and native user interfaces

Support
    Quality
      Security
        License
          Reuse

            reactby facebook

            JavaScript doticon star image 209050 doticonVersion:v18.2.0doticon License: Permissive (MIT)

            The library for web and native user interfaces
            Support
              Quality
                Security
                  License
                    Reuse

                      You can also search for any dependent libraries on kandi like 'react'.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.

                      See similar Kits and Libraries