React Form with JSX

Before starting on a creating form with JSX, we must be aware of JSX form libraries. Generally, HTML form element inputs take their value as display text/values, but in React JSX, they take property values of respective elements and display them. As we have already visually perceived that we can't change props' values directly, so the input value won't have that transmuted value as an exhibit value.

Let's discuss this in detail. To change the value of a form input, you will use the value attribute and then you will see no change. This doesn't mean that we cannot change the form input value, but for that, we need to listen to the input events, and you will see that the value changes.

The following exceptions are self-explanatory, but very important:

Label content will be considered as a value prop in React. As for is a reserved keyword of JavaScript; the HTML for the attribute should be bounded like the HTML for a prop. You'll have a better understanding when you look at the next example. Now, it's time to learn that to have form elements in the output, we need to use the following script, and we also need to replace it with the previously written code.

Now, let's start on building an Add Ticket form for our application. Create a reactForm.html file in the root and and react-form.js file in <strong>js folder. The following code snippet is just a base HTML page that includes Bootstrap CSS and React.

Here's the markup of our HTML page:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add ticket form with JSX</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<script crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-
dom.development.js"></script>
<script src="https://unpkg.com/babel-
[email protected]/babel.min.js"></script>
</body>
</html>

It is always a good practice to load all your scripts at the bottom of the page before your <body> tag closes, which loads the component successfully in your DOM, because when the script is executed in the <head> section, the document element is not available as the script itself is in the <head> section. The best way to resolve this problem is to keep scripts at the bottom of your page before your <body> tag closes, and it will be executed after loading all your DOM elements, which will not throw any JavaScript errors.

Since JSX is similar to JavaScript, we can't use the class attribute in JSX because it's a reserved keyword in JavaScript. We should use className and htmlFor as property names in the ReactDOM component.

Now, Let's create some HTML layout in this file with bootstrap

 <div class="container">
<div class="row">
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HelpDesk</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Add Ticket</a></li>
</ul>
</div>
</div>
</nav>
<div class="col-lg-12">
<h2>Add Ticket</h2>
<hr/>
<div id="form">
<!-- Here we'll load load our AddTicketForm component with help of "form" id -->
</div>
</div>
</div>
</div>

In the above code we have created the navigation and wrapped it into the bootstrap grid classes for responsive behavior of the component. 

This is how our HTML looks in the browser.

For our Add Ticket form  component,  we need the following form fields along with the label:

  • Email: <input>
  • Issue type: <select>
  • Assign department<select>
  • Comments<textarea>
  • Button<button>

Also, here's the list of supported events:

  • onChange, onInput, and onSubmit
  • onClick, onContextMenu, onDoubleClick, onDrag, and onDragEnd
  • onDragEnter and onDragExit
  • onDragLeave, onDragOver, onDragStart, onDrop, and onMouseDown
  • onMouseEnter and onMouseLeave
  • onMouseMove, onMouseOut, onMouseOver, and onMouseUp

Let's take a quick look at our form's component code in react-form.js:

class AddTicketForm extends React.Component {
constructor() {
super();
this.handleSubmitEvent = this.handleSubmitEvent.bind(this);
}
handleSubmitEvent(event) {
event.preventDefault();
}
render() {
var style = {color: "#ffaaaa"};
return ( <form onSubmit = {this.handleSubmitEvent}>
<div className = "form-group">
<label htmlFor = "email"> Email <span style = {style}> * </span></label>
<input type = "text" id = "email" className = "form-control" placeholder = "Enter your email address" required />
</div>
<div className = "form-group">
<label htmlFor = "issueType"> Issue Type <span style = {style}> * </span></label>
<select className = "form-control" id = "issueType" required>
<option value = ""> -- -- - Select-- -- < /option>
<option value = "Access Related Issue"> Access Related Issue </option>
<option value = "Email Related Issues"> Email Related Issues </option>
<option value = "Hardware Request"> Hardware Request</option>
<option value = "Health & Safety"> Health & Safety </option>
<option value = "Network"> Network </option>
<option value = "Intranet"> Intranet </option>
<option value = "Other"> Other </option>
</select>
</div>
<div className = "form-group">
<label htmlFor = "department"> Assign Department
<span style = {style} > * </span>
</label>
<select className="form-control" id="department" required>
<option value = ""> -- -- - Select-- -- </option>
<option value = "Admin" > Admin </option>
<option value = "HR"> HR </option>
<option value = "IT"> IT </option>
<option value = "Development"> Development </option>
</select>
</div>
<div className = "form-group">
<label htmlFor = "comments"> Comments
<span style = {style}> * </span>
</label>
( <span id = "maxlength"> 200 </span> characters max)
<textarea className = "form-control" rows = "3" id = "comments" required> </textarea>
</div>
<div className = "btn-group">
<button type = "submit" className = "btn btn-primary"> Submit </button>
<button type = "reset" className = "btn btn-default"> cancel </button>
</div>
</form>
);
}
});
ReactDOM.render( <AddTicketForm /> ,
document.getElementById('form')
);

To apply a style or call an onSubmit() function in the attribute value, rather than using quotes (""), we have to use a pair of curly braces ({}) in the JavaScript expression. It means that you can embed any JavaScript expression in JSX by wrapping it in curly braces, even a function.

Add this script tag at the bottom of the HTML page after the react libraries

<script src="js/react-form.js" type="text/babel"></script>

Now, open your browser and let's take a look at the output of our JSX code:

That looks awesome. We can see our form as expected.

The first character should always be capitalized when you create a component in React. For example, our Add Ticket form component is <AddTicketForm></AddTicketForm>.

For the large-scale application, this approach will not be recommended; we cannot put the whole JSX code at one place every time we create form elements. To make our code clean and manageable, we should create a reusable component and just give the reference of that component wherever we need to use it.

So let's see how we can achieve this in our existing code, and we will create one reusable text input component:

const TextInput = ({
type,
name,
label,
onChange,
placeholder,
value,
required
}) => {
return ( <div className = "form-group">
<label htmlFor = {name} > {label} </label>
<div className = "field">
<input type = {type} name = {name} className ="form-control" placeholder = { placeholder} value = {value} onChange = {onChange} required = {required}/>
</div>
</div>
)
}

In the preceding code snippet, we created one object that takes some arguments related to the input attribute and assigned those arguments' values to attributes' value:

<TextInput
type="email"
name="email"
label="Email"
placeholder="Enter your email address"
required={true}/>

Now we just need to add the preceding TextInput component like this in our render method, as you can see in the preceding code, rather than adding the label and input every time in our application; that shows the power of ReactJS.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset