We now have a youtube channel. Subscribe!

ReactJS | Uncontrolled Component

ReactJS | Uncontrolled Component


Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about ReactJS uncontrolled component.

As we studied in our previous tutorial post, uncontrolled component does not support React based form programming. Getting a value of a React DOM element isn't possible without using React api. One way to get the content of the react component is by using React ref feature.

React makes available a ref attribute for all its DOM elements and a corresponding api, React.createRef() to create a new reference this.ref. The newly created reference can be attached to form element and the attached form element's value can be accessed using this.ref.current.value whenever necessary (during validation and submission).

Let us now see the step by step process to perform form programming in uncontrolled component.

Create a reference.

this.inputRef = React.createRef();

Next, create a form element.

<input type="text" name="username" />

Attach the already created reference in the form element.

<input type="text" name="username" ref={this.inputRef} />

To set the default value of an input element, use defaultValue attribute rather than value attribute. If value is used, it will get updated during rendering phase of the component.

<input type="text" name="username" ref={this.inputRef} defaultValue="default value" />

Lastly, get the input value by making use of this.inputRef.current.value during validation and submission.

handleSubmit(e) {
   e.preventDefault();

   alert(this.inputRef.current.value);
}


Let us create a simple form to add expense entry using uncontrolled component in this tutorial.

First, create a new react application, react-form-uncontrolled-app via Create React App or Rollup bundler by following guidelines in Creating a React application tutorial.

Next, open the application in your favorite editor.

Next, create an src folder beneath the root directory of the application.

Next, create a component folder under src folder.

Next, create a file, ExpenseForm.css under src folder to style the component.

input[type=text], input[type=number], input[type=date], select {
   width: 100%;
   padding: 12px 20px;
   margin: 8px 0;
   display: inline-block;
   border: 1px solid #ccc;
   border-radius: 4px;
   box-sizing: border-box;
}

input[type=submit] {
   width: 100%;
   background-color: #4CAF50;
   color: white;
   padding: 14px 20px;
   margin: 8px 0;
   border: none;
   border-radius: 4px;
   cursor: pointer;
}

input[type=submit]:hover {
   background-color: #45a049;
}

input:focus {
   border: 1px solid #d9d5e0;
}

#expenseForm div {
   border-radius: 5px;
   background-color: #f2f2f2;
   padding: 20px;
}

Next, create a file, ExpenseForm.js beneath src/components folder and start editing.

Next, import React library.

import React from 'react';

Next, import ExpenseForm.css file.

import './ExpenseForm.css'

Next, create a class, ExpenseForm and call constructor with props.

class ExpenseForm extends React.Component {
   constructor(props) {
      super(props);
   }
}

Next, create a React reference for all input fields.

this.nameInputRef = React.createRef();
this.amountInputRef = React.createRef();
this.dateInputRef = React.createRef();
this.categoryInputRef = React.createRef();

Next, create a render() method and add a form with input fields to add expense items.

render() {
   return (
      <div id="expenseForm">
         <form>
            <label for="name">Title</label>
            <input type="text" id="name" name="name" placeholder="Enter expense title" />

            <label for="amount">Amount</label>
            <input type="number" id="amount" name="amount" placeholder="Enter expense amount" />

            <label for="date">Spend Date</label>
            <input type="date" id="date" name="date" placeholder="Enter date" />

            <label for="category">Category</label>
            <select id="category" name="category" >
               <option value="">Select</option>
               <option value="Food">Food</option>
               <option value="Entertainment">Entertainment</option>
               <option value="Academic">Academic</option>
            </select>

            <input type="submit" value="Submit" />
         </form>
      </div>
   )
}

Next add an event handler for the submit action.

onSubmit = (e) => {
   e.preventDefault();

   let item = {};

   item.name = this.nameInputRef.current.value;
   item.amount = this.amountInputRef.current.value;
   item.date = this.dateInputRef.current.value;
   item.category = this.categoryInputRef.current.value;

   alert(JSON.stringify(item));
}


Next, attach the event handlers to the form.

render() {
   return (
      <div id="expenseForm">
         <form onSubmit={(e) => this.onSubmit(e)}>
            <label for="name">Title</label>
            <input type="text" id="name" name="name" placeholder="Enter expense title" 
               ref={this.nameInputRef} />

            <label for="amount">Amount</label>
            <input type="number" id="amount" name="amount" placeholder="Enter expense amount" 
               ref={this.amountInputRef} />      

            <label for="date">Spend Date</label>
            <input type="date" id="date" name="date" placeholder="Enter date" 
               ref={this.dateInputRef} />

            <label for="category">Category</label>
            <select id="category" name="category" 
               ref={this.categoryInputRef} >
               <option value="">Select</option>
               <option value="Food">Food</option>
               <option value="Entertainment">Entertainment</option>
               <option value="Academic">Academic</option>
            </select>

            <input type="submit" value="Submit" />
         </form>
      </div>
   )
}

Finally, export the component.

export default ExpenseForm

Following below is the complete code of the ExpenseForm component.

import React from 'react';
import './ExpenseForm.css'

class ExpenseForm extends React.Component {
   constructor(props) {
      super(props);

      this.nameInputRef = React.createRef();
      this.amountInputRef = React.createRef();
      this.dateInputRef = React.createRef();
      this.categoryInputRef = React.createRef();
   }
   onSubmit = (e) => {
      e.preventDefault();
      let item = {};
      item.name = this.nameInputRef.current.value;
      item.amount = this.amountInputRef.current.value;
      item.date = this.dateInputRef.current.value;
      item.category = this.categoryInputRef.current.value;

      alert(JSON.stringify(item));
   }
   render() {
      return (
         <div id="expenseForm">
            <form onSubmit={(e) => this.onSubmit(e)}>
               <label for="name">Title</label>
               <input type="text" id="name" name="name" placeholder="Enter expense title" 
                  ref={this.nameInputRef} />

               <label for="amount">Amount</label>
               <input type="number" id="amount" name="amount" placeholder="Enter expense amount" 
                  ref={this.amountInputRef} />   

               <label for="date">Spend Date</label>
               <input type="date" id="date" name="date" placeholder="Enter date" 
                  ref={this.dateInputRef} />

               <label for="category">Category</label>
               <select id="category" name="category" 
                  ref={this.categoryInputRef} >
                 <option value="">Select</option>
                 <option value="Food">Food</option>
                 <option value="Entertainment">Entertainment</option>
                 <option value="Academic">Academic</option>
               </select>
              
               <input type="submit" value="Submit" />
           </form>
         </div>
      )
   }
}
export default ExpenseForm;

Next, create a file, index.js beneath the src folder and use ExpenseForm component.

import React from 'react';
import ReactDOM from 'react-dom';
import ExpenseForm from './components/ExpenseForm'

ReactDOM.render(
   <React.StrictMode>
      <ExpenseForm />
   </React.StrictMode>,
   document.getElementById('root')
);

Finally, create a public folder under the root folder and create index.html file.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>React App</title>
   </head>
   <body>
      <div id="root"></div>
      <script type="text/JavaScript" src="./index.js"></script>
   </body>
</html>

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.

root_folder

Finally, enter a sample expense details and click on submit. The submitted data will be collected and showed in a pop-up message box.



Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about ReactJS Formik.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain