React, React How To

How to add JSX to a Form in React?

Written by Rohit Gupta · 3 min read >

In the last article, we created the UI of our application using HTML5 and Bootstrap.

If you have not gone through the previous article, you can read it here.

To learn what is JSX, visit.

React Form UI

Before I start to code the logic for each element, I would like to give you an idea, what hooks are? since I will be using the useState hook,

Hooks in React

Hooks are a new functionality that was introduced in React 16.8. It enables you to leverage state and other React capabilities without having to create a class. Hooks are functions that allow functional components to “hook into” React state and lifecycle features. Hooks are backward-compatible, which means there are no breaking changes.

Rules of Hooks

Hooks are identical to JavaScript functions, but while utilizing them, you must obey these two requirements. Hooks rule guarantees that all of a component’s stateful functionality is visible in its source code. These rules are:

1. Only call Hooks at the top level

Hooks should not be called within loops, conditions, or nested functions. Hooks should be used at the top level of React functions at all times. This rule guarantees that Hooks are called in the same sequence every time a component renders.

2. Only call Hooks from React functions

Hooks cannot be called from ordinary JavaScript functions. Hooks can instead be called from React function components.

Types of Hooks

  • Basic Hooks
    • useState
    • useEffect
    • useContext
  • Additional Hooks
    • useReducer
    • useCallback
    • useMemo
    • useRef
    • useImperativeHandle
    • useLayoutEffect
    • useDebugValue

Tip: You can read about useState hooks here.

preventDefault in React

The preventDefault() function cancels the event if it is cancelable, which means that the event’s default action will not take place.

For example, this can be useful when:

  • Clicking on a “Submit” button, prevent it from submitting a form
  • Clicking on a link, prevent the link from following the URL

Tip

  1. Not all events can be canceled. To determine whether an event is cancelable, use the cancelable attribute.
  2. The preventDefault() function does not prevent an event from propagating farther across the DOM. To address this, use the stopPropagation() function.

Creating useState Hook

I am using useState hook, to store the state of the elements, i.e. the values entered by the user.

const [form, setform] = useState({
    name: '',
    mobile: '',
    email: '',
    dropdown: '',
    order: ''
  })

I created an useState hook named “form”, containing:

  • name – to store “Name”
  • mobile – to store “Mobile”
  • email – to store “E-Mail”
  • dropdown – to store “Menu”
  • order – to store “Order Details”
const inputHandler = (e) => {
    setform({ ...form, [e.target.name]: e.target.value })
}

const submitButton = (e) => {
    e.preventDefault()
    console.log(form)

    if (form.name === '' || form.mobile === '' || form.email === '' || form.dropdown === '' || form.order === '') {
      alert('Please fill all the fields')
    } 
    else {
      resetButton()
    }
}

const resetButton = (e) => {
    setform({
      name: '',
      mobile: '',
      email: '',
      dropdown: '',
      order: ''
    })
}

All the above functions take event ‘e’ as input. You can read more Event Handling in React, here.

inputHandler()

This function accepts the target values from the event and stores them with the corresponding target name.

Tip: “…form” is used so that when a form is resubmitted, the past values are not lost. Instead, the new values are appended to the old values.

All the values are saved in JSON format inside the “form”, using the setform().

submitButton()

This function is called when we need to submit the form.

It will first prevent the event default behavior and then log the content of the “form”.

I have added validation, using the following code:

if (form.name === '' || form.mobile === '' || form.email === '' || form.dropdown === '' || form.order === '') {
      alert('Please fill all the fields')
    } 

This code will throw an alert message if any of the fields remain unselected.

Tip: You can use different types of validations by writing your code, or using some APIs.

If the data is successfully logged, we call the resetButton() to clear the content of the form.

resetButton()

This function clears the content of the form. To clear the content we will assign empty values to each of the fields using the setform().

HTML Code

So we are done writing our JSX code for logic. Now we need to connect them to the elements.

We need to add 3 values to each of the elements:

  1. Name : name of the element for the hook.
  2. value: value of the element coming from the hook.
    Format: [hooksName].[elementName]
  3. onChange: function to be called from each of the element.
    for submit button: submitButton
    for reser button: resetButton
    for everything else: inputHandler

So after filling in the above values, the code will look like

<div className="container mt-3 mb-3">
   <div className="mb-3">
      <label htmlFor="exampleFormControlInput1" className="form-label">Name</label>
      <input type="name" name="name" className="form-control" value={form.name}
         onChange={inputHandler} id="exampleFormControlInput1" />
   </div>
   <div className="mb-3">
      <label htmlFor="exampleFormControlInput1" className="form-label">Mobile</label>
      <input type="mobile" value={form.mobile} onChange={inputHandler}
         name="mobile" className="form-control" id="exampleFormControlInput1" />
   </div>
   <div className="mb-3">
      <label htmlFor="exampleFormControlInput1" className="form-label">Email address</label>
      <input type="email" value={form.email} onChange={inputHandler}
         name="email" className="form-control" id="exampleFormControlInput1"
         placeholder="[email protected]" />
   </div>
   <div className="mb-3">
      <label htmlFor="sel1">Menu</label>
      <select name="dropdown" value={form.dropdown} className="form-control" id="sel1" onChange={inputHandler}>
         <option value="Select">Select</option>
         <option value="Veg Biryani">Veg Biryani</option>
         <option value="BBQ Chicken Wings">BBQ Chicken Wings</option>
         <option value="Rasmalai">Rasmlai</option>
         <option value="Beer">Beer</option>
      </select>
   </div>
   <div className="mb-3">
      <label htmlFor="exampleFormControlTextarea1" className="form-label">Order Details</label>
      <textarea name="order" value={form.order} onChange={inputHandler}
         className="form-control" id="exampleFormControlTextarea1"
         rows="3"></textarea>
   </div>
   <div className="mb-3">
      <button type='submit' onClick={submitButton} className="btn btn-success">Submit</button>
      <button type='reset' onClick={resetButton} className="btn btn-danger">Cancel</button>
   </div>
</div>
</>

You can find my code, here.

Conclusion

Thanks for reading, hope you got answers to some of your questions and learned how to create a simple Form UI in React.

Visit Let’s React to learn more about React.

Loading

Written by Rohit Gupta
C# Corner MVP Program Director. I am an Intel® AI Edge Scholar, ML & Cognitive Robotics Enthusiast, and 2 times C# Corner MVP. I feel that bonding between Machines and Humans will make this world a better place. I aspire to be the first person to make a general-purpose human-like humanoid. I used "human" 2 times because no technology can ever have what we call "Insaniyat". https://www.linkedin.com/in/rohit-gupta-04578471/ https://hindikijiwani.blogspot.com/ Profile

2 Replies to “How to add JSX to a Form in React?”

Leave a Reply

Your email address will not be published. Required fields are marked *