0
0
Reactframework~30 mins

Preventing default behavior in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Preventing Default Behavior in React
📖 Scenario: You are building a simple React web page with a form. When the user clicks the submit button, the page should not reload. Instead, you want to show a message that the form was submitted.
🎯 Goal: Create a React functional component with a form. Prevent the form's default submit behavior so the page does not reload. Show a message when the form is submitted.
📋 What You'll Learn
Create a React functional component named SubmitForm.
Add a form with a submit button inside the component.
Use an event handler function named handleSubmit for the form's onSubmit event.
Inside handleSubmit, prevent the default form submission behavior using event.preventDefault().
Show a message Form submitted! below the form when the submit button is clicked.
💡 Why This Matters
🌍 Real World
Preventing default form submission is common in web apps to handle data without reloading the page, improving user experience.
💼 Career
Understanding event handling and preventing default behavior is essential for frontend developers working with React or other frameworks.
Progress0 / 4 steps
1
Create the React component with a form
Create a React functional component named SubmitForm. Inside it, return a <form> element with a submit button labeled Submit.
React
Need a hint?

Start by writing a function named SubmitForm that returns a form with a submit button.

2
Add the submit handler function
Inside the SubmitForm component, create a function named handleSubmit that takes an event parameter.
React
Need a hint?

Define a function named handleSubmit inside the component that accepts event as a parameter.

3
Prevent the default form submission
Inside the handleSubmit function, call event.preventDefault() to stop the form from reloading the page when submitted.
React
Need a hint?

Use event.preventDefault() inside handleSubmit to stop the page reload.

4
Connect the handler and show submission message
Add the onSubmit attribute to the <form> element and set it to {handleSubmit}. Also, add a React state variable named submitted initialized to false. Inside handleSubmit, set submitted to true. Below the form, conditionally render a <p> element with the text Form submitted! only when submitted is true.
React
Need a hint?

Use React's useState to track submission. Attach handleSubmit to the form's onSubmit. Show the message only when submitted is true.