Monday, 25 November 2024

Form Handling in React: Understanding event.preventDefault()

When a Form data is submitted, the browser reloads the page (or navigates to the response page if specified in the action). This is because submitting a form triggers a new HTTP request, and the browser expects a new page or an update. This default behavior can be undesirable in single-page applications (SPAs) like React, where form submissions should be handled without refreshing the entire page. Hence, event.preventDefault() is often used to stop this default behavior and allow custom form handling.

Let me explain the default behavior with an example.

 

SubmitComment.jsx

import React, { useState } from "react";

export default function LoginForm() {
  return (
    <form method="post" action="/api/comments">
      <label htmlFor="comment">Enter Your Comment</label>
      <br />
      <input type="text" id="comment" name="comment" required/>
      <br />
      <br />

      <button type="submit">Post Comment</button>
    </form>
  );
}

 

Above snippet generate below screen.

 


 

When the ‘Post Comment’ button is clicked, the user’s input is submitted to the action URL /api/comments, which causes the page to redirect to the /api/comments endpoint. However, we can prevent this default behavior by using the event.preventDefault() method. Same behavior is depicted in below screen.

 



How to prevent this default behavior?

We can prevent this default behavior by handing this submit event explicitly.

import React, { useState } from "react";

export default function LoginForm() {
  const [inputValue, setInputValue] = useState("");

  const handleLogin = (event) => {
    event.preventDefault();

    alert("Comment Posted Successfully Successfully!!!!");

    setInputValue("");
  };

  // Handler for input change to update state
  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <form method="post" action="/api/comments" onSubmit={handleLogin}>
      <label htmlFor="comment">Enter Your Comment</label>
      <br />
      <input
        type="text"
        id="comment"
        name="comment"
        value={inputValue}
        onChange={handleInputChange}
      />
      <br />
      <br />

      <button type="submit">Post Comment</button>
    </form>
  );
}

 

When the form is submitted, instead of proceeding with the default form submission behavior, it triggers the handleLogin function.

 

Within the handleLogin function,

 

1.   The event.preventDefault() method prevents the form from redirecting or refreshing the page after submission.

2.   An alert is shown with the message "Comment Posted Successfully!".

3.   The input field is then reset by setting the inputValue to an empty string.

 

This prevents the page from being redirected to the /api/comments endpoint and handles the form submission logic within React itself.

 

 

Follow below step-by-step procedure to build the complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project

‘prevent-default-form-submission-behavior’.

 

Project structure looks like below. 


 

Step 2: Create components folder in src/ folder and define LoginForm component.

 

SubmitComment.jsx

import React, { useState } from "react";

export default function LoginForm() {
  const [inputValue, setInputValue] = useState("");

  const handleLogin = (event) => {
    event.preventDefault();

    alert("Comment Posted Successfully Successfully!!!!");

    setInputValue("");
  };

  // Handler for input change to update state
  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <form method="post" action="/api/comments" onSubmit={handleLogin}>
      <label htmlFor="comment">Enter Your Comment</label>
      <br />
      <input
        type="text"
        id="comment"
        name="comment"
        value={inputValue}
        onChange={handleInputChange}
        required
      />
      <br />
      <br />

      <button type="submit">Post Comment</button>
    </form>
  );
}

Step 3: Update main.jsx like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import SubmitComment from './components/SubmitComment'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <SubmitComment />
  </StrictMode>,
)

Step 4: Build and run the Application by executing below commands.

cd prevent-default-form-submission-behavior
npm install
npm run dev

Open the url ‘http://localhost:5173/ in browser, you will see below kind of screen.

 



Enter some comment and click on the button ‘Post Comment’ button, you will see an alert message like below.

 

Click on OK button, you will be in the same page and the text box is cleared.

 

You can download the application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment