Skip to content

Instantly share code, notes, and snippets.

@MenarSelamet
Last active June 4, 2024 11:49
Show Gist options
  • Save MenarSelamet/623832dc4b4a02b03872d8588c559909 to your computer and use it in GitHub Desktop.
Save MenarSelamet/623832dc4b4a02b03872d8588c559909 to your computer and use it in GitHub Desktop.

React Froms and Events

  1. What is the difference between controlled and uncontrolled components in React? Provide examples of each.
  2. How does event handling work in React forms?
  3. How do you prevent the default behavior of a form submission in React?
  4. How can you display the data entered into a form below the form in real-time?
  5. How do you manage the state of a form input in React?
@katmafalela
Copy link

  1. Controlled Components: The state of the React component contains the data (passwords and usernames, for example). React is now the only reliable source for the information contained in the form.
    An event handler is a function you write that is triggered each time the user types in an input field. The new data is added to the component's state by this function.
    After that, React updates the component's rendering with the new data.

function UsernameInput() {
const [username, setUsername] = useState("");

const handleChange = (event) => {
setUsername(event.target.value);
}

return (


Username:


);
}

Uncontrolled elements operate somewhat differently. Here, the value attribute of the form element is used to store the data directly in the DOM, which is the browser's built-in method of displaying your web page. This value is not under the direct control of React.

You use Refs to gain access to the data. You can obtain a reference to the actual DOM element by using a Ref. After that, you can obtain the most recent data by using the element's.value property.
For very simple forms, uncontrolled components may be easier to handle, but for more complex forms, they may become more difficult.

function FavoriteColor() {
const colorRef = useRef(null);

const handleSubmit = (event) => {
event.preventDefault();
const color = colorRef.current.value;
console.log("Favorite Color:", color);
}

return (


Favorite Color:

Submit

);
}

  1. Event handling in React forms is all about capturing user interactions with the form elements (like input fields, buttons) and taking some action in response. React uses a concept called synthetic events to achieve this.

  2. There are two main ways to prevent the default form submission behavior in React:

  3. Using event.preventDefault() in the Event Handler:

This is the most common approach. When you define your event handler function for the form submission (usually with the onSubmit prop on the form element), you can use event.preventDefault() within the function to stop the default behavior.

Here's an example:

function MyForm(props) {
  const handleSubmit = (event) => {
    event.preventDefault(); // Prevent default form submission
    // Your form handling logic here (e.g., form validation, data processing)
    console.log("Form Submitted!");
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Your form fields here */}
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, clicking the submit button triggers the handleSubmit function. By calling event.preventDefault(), we stop the browser from reloading the page (the default behavior). This allows you to handle the form submission within your React component, such as performing validation or sending data to a server.

  1. Setting the type attribute of the submit button to button:

While less common, you can achieve the same outcome by changing the type attribute of the submit button itself. By default, submit buttons have a type="submit" which triggers form submission. Changing it to type="button" transforms the button into a regular button element and prevents the default behavior.

Here's an example:

function MyForm(props) {
  const handleSubmit = (event) => {
    // Your form handling logic here
    console.log("Form Submitted!");
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Your form fields here */}
      <button type="button" onClick={handleSubmit}>Submit</button>
    </form>
  );
}

In this approach, we use a regular button with type="button" and attach an onClick event handler to it. Clicking the button triggers the handleSubmit function, allowing you to implement your custom form handling logic.

Choosing the Right Method:

The first approach (event.preventDefault()) is generally recommended as it provides more flexibility and allows you to potentially leverage other event properties within the handler function. The second approach might be simpler for very basic forms, but it decouples the button functionality from the form submission itself.

  1. There are two main ways to manage the state of a form input in React, depending on how you want to handle the data:

Controlled Components:
This is the recommended approach for most cases. In controlled components, the form data (like the value of an input field) is stored in the React component's state. This makes React the single source of truth for what's in the form.

Here's how it works:

You define a state variable using React's useState hook to hold the current value of the input field.
The input element's value attribute is set to the state variable, essentially syncing the displayed value with the state.
Whenever the user interacts with the input field (e.g., typing), an event handler function (usually with onChange) is triggered.
This event handler function updates the component's state with the new value from the event object (typically event.target.value).
React re-renders the component with the updated state, reflecting the change in the input field.
Example:

JavaScript
function NameInput() {
const [name, setName] = useState("");

const handleChange = (event) => {
setName(event.target.value);
}

return (


Name:


);
}
Use code with caution.
content_copy
In this example, the name state variable holds the current name entered by the user. The handleChange function updates the state whenever the user types something new.

Benefits of Controlled Components:

Predictable Behavior: Easier to track and manage form data changes.
Validation: You can implement validation logic within the event handler before updating the state.
Uncontrolled Components:
Uncontrolled components are less common but can be suitable for very basic forms. Here, the data is stored directly in the DOM (the browser's built-in way of representing your web page) using the value attribute of the form element. React doesn't directly control this value.

To access the data, you can use Refs. A Ref allows you to grab a reference to the DOM element itself. You can then use the element's .value property to get the current data.
Uncontrolled components can be simpler for basic forms, but for more complex forms, they can get trickier to manage form state and validation.
Example:

JavaScript
function FavoriteColor() {
const colorRef = useRef(null);

const handleSubmit = (event) => {
event.preventDefault();
const color = colorRef.current.value;
console.log("Favorite Color:", color);
}

return (


Favorite Color:

Submit

);
}
Use code with caution.
content_copy
In this example, the colorRef ref holds a reference to the color input element. The handleSubmit function uses this reference to access the current color value.

Choosing the Right Approach:

Controlled components are generally recommended for most form scenarios in React. They offer better predictability, easier validation, and a more controlled development experience. Uncontrolled components might be suitable for super simple forms or integrating with external libraries that manage their own state.

@Hophneylen
Copy link

Lentsoana Hophney
Angela King
Thabiso Makolana

  1. In React forms, controlled components manage data with the component's state, offering validation and control. Uncontrolled components use DOM refs for simpler forms, but have less control over the data.
    For example, a controlled input field keeps track of its value in the component's state, while an uncontrolled one uses a ref to access the value directly from the DOM element.

2.In React forms, event handlers (like onChange or onSubmit) are functions that listen for user interactions and execute code in response.

3.When you define an onSubmit handler for your React form, you must include event.preventDefault() within the function. This stops the browser's default behavior of reloading the page when the form is submitted, allowing you to handle the submission logic within your React component.

4.Controlled components enable direct display of form data within the component's render function by referencing the component's state.
The data displayed will be updated synchronously as the user types.

5.Use the useState hook to create state variables for each form input. Update these state variables within the onChange event handlers when the user modifies the input fields.

@LethuM2197
Copy link

Lethukuthula
with @sthabiso-iv

  1. Controlled components give you more control and make it easier to manage form data in your React app. Uncontrolled components are simpler to set up for basic forms, but can be trickier to manage complex forms.
  2. First have to define form elements, set up state, attach and write event handlers with their functions, then finally access and update useState the re-render the form.
  3. You change the event.preventDefault() method inside the handler function.
  4. Using the useState hook.
  5. By stating with the useState hook

@NokulungaM
Copy link

Nokulunga
Nhlanhla
Konanani

  1. Controlled Components - Controlled components in React refer to components where the form data is handled by the React component
    itself, rather than the DOM. This means that the state of the form elements is controlled by the React state. This approach provides a single
    source of truth for form data, making it easier to manage and debug.
    Example : Controlled Input Text Field, Controlled Checkbox

    Uncontrolled Components - Uncontrolled components in React are components where the form data is handled by the DOM itself rather
    than
    by the React component. This means that form elements like inputs can maintain their own state without any direct management by React.
    Uncontrolled components can be useful when you need to quickly integrate existing non-React libraries or when you need less control over
    the form elements.
    Example : Input Type File

  2. To handle events in React, developers can define event handlers in their components using a special syntax, such as onClick for mouse click events or onChange for input change events. The event handlers can be defined as class methods or as arrow functions within the component.

  3. In React, you can prevent the default behavior of a form submission by using the preventDefault() method on the event object passed to the submission handler.

  4. To display the data entered into a form below the form in real-time, you can use the state to store the form data and render it below the form.

  5. In React, you can manage the state of a form input using the useState hook.

  • Define a variable to hold the form input values
  • Ensure that the input value is always in sync by binding it to the state variable
  • Use an event handler for updating the state variable when the user interacts with the form input.

@KhileM
Copy link

KhileM commented Jun 4, 2024

Mpilo
Emihle
Sakhile

  1. In React, components can be controlled or uncontrolled in how they handle form data:
    Controlled Components:
    React state manages form data (single source of truth).
    Updates trigger re-renders for validation and control.
    Example: Controlled input field with onChange handler updating state.

Uncontrolled Components:
DOM manages form data using refs.
Less code for simple forms, but trickier for complex ones.
Example: Input field with ref to access DOM value at submit.
Generally, controlled components are preferred for predictability and validation.

  1. In React forms, event handlers defined in your component are attached to form elements like onChange in JSX. These handlers receive an event object containing the new value when triggered by user interactions. You can then access this value and update your component's state using useState, causing React to re-render the form with the latest data, creating a responsive and dynamic form experience.

  2. To prevent the default form submission behavior in React, you can utilize the event.preventDefault() method within your form's onSubmit event handler. This halts the browser's default action (usually a page refresh) and allows you to control the submission process. You can then perform tasks like data validation or handle the submission with an API call before allowing the form to potentially submit.

  3. In React, controlled components allow you to manage form data within your component's state. By using the onChange event handler on form elements (like inputs), you can update the state with the new value whenever the user types. This updated state can then be displayed below the form using JSX, effectively showing the user's input in real-time.

  4. In React, form inputs are typically managed using controlled components. This means the component's state holds the single source of truth for the form data. When a user types, the onChange event handler captures the new value and updates the state using useState. React then re-renders the form with the updated state, keeping the displayed value and component state in sync.

@samuelthis
Copy link

@NtokozoMitchell
@Yenkosii
@samuelthis

  1. In React, controlled components are like children whose actions are determined by their parent component. The parent component holds the form data in its state and dictates how the controlled component should behave, for example: The child is the component (like an input field) or forms. While, uncontrolled components are independent actors. They manage their state and actions without relying on a parent component to dictate their behaviour, for example: The child components are free to move and act on their own and, keep track of their own actions and positions.

  2. React form event handling involves creating functions for user interactions, attaching them to form elements with event attributes, and using event.preventDefault() to stop default browser actions.

  3. To prevent the default behaviour of a form submission in React, you use the event.preventDefault() method in your event handler function. This method stops the form from submitting traditionally, which would cause a page to reload. Instead, it allows you to handle the form submission asynchronously with JavaScript, the React way of handling forms.

  4. In React, you can instantly show what's being typed into a form right below it. This is done by using React's state management to update the display as the user types.

  5. In React, you manage the state of a form input by using a component's state to store the input values and updating the state in response to user input events, typically using an onChange event handler.

@PhamelaMhlaba
Copy link

Team Members(Phamela, Lindokuhle and Gerald)

Answers.

  1. Controlled Components
    State Management: Controlled components keep the form data (like input values) in the React state of the
    component or its parent.

    Example - An input field whose value is updated by React state changes.

    Uncontrolled Components
    State Management: Uncontrolled components rely on the DOM itself to manage the form data. You
    access the current value using React Refs.

    Example - An input field whose value is read directly from the DOM when needed using a ref.

  2. In React forms, event handling works by attaching event handlers (e.g., onChange, onSubmit) to form elements, which call functions to update the component's state or perform actions when the user interacts with the form. This ensures that React can manage and respond to user input in a controlled manner.

  3. In React, you can prevent the default form submission behavior using the event.preventDefault() method within your form's submit handler function. This function is typically triggered when the submit button is clicked.

  4. Target Inputs: Use document.getElementById to access each form input element by its unique ID.
    Event Listeners: Attach an event listener (like keyup for text input) to capture user interaction.
    Update Display: Inside the listener, retrieve the current value using element.value.
    Display Data: Update the content of a designated HTML element (e.g., a

    ) with the captured value.

  5. React forms use a concept called "controlled components" to manage form input state.

    State Hook: Use the useState hook to define a state variable for each form field's value.
    Controlled Input: Set the value attribute of the input element to the corresponding state variable.
    Update on Change: Create an event handler function that updates the state with the new value from the
    onChange event.

@Gracepinkie
Copy link

Koketso:
Sinethemba:
1.Controlled components are those in which form data is handled by the component’s state e.g When the user interacts with an input element (e.g., types in a text field), the component’s state is updated accordingly .Uncontrolled components are those in which form data is handled by the DOM itself e.g The DOM manages the form data directly without the component’s explicit control.
The input elements store their own state internally.

  1. Event handling in React forms involves using event listeners like onChange, onSubmit, etc. React wraps the native browser events into a synthetic event, which has the same interface as the native event but works identically across all browsers.
  2. To prevent the default behavior of a form submission, you use the event.preventDefault() method within the onSubmit event handler.
  3. To display form data in real-time, you can use state to keep track of the input value and render it below the form. The DisplayData component will automatically reflect the changes in real-time.
  4. To manage the state of a form input, you use React's useState hook for functional components or this.state and this.setState for class components.

@Sharolinah-23
Copy link

Sharon Matjila
Wesley Mutyambizi
Selepe Thiane

  1. A controlled component is when a React component handles all form data. For an uncontrolled component, the values of inputs from a form are held in the DOM and must be retrieved using “ref”.
    Controlled Component:
    Imagine a form to write your name. Here, React controls the input field like a magic notepad:
    You define a variable (name) to hold your name (using React's magic).
    The input field is linked to this variable, showing what you type.
    Whenever you type, the magic updates your name variable.

Uncontrolled Component:
This time, the input field is like a regular notepad:
The input field has no magic link to React.
You type your name directly on the field.
To get your name later (e.g., when submitting the form), you have to reach into the field and grab the value.

  1. Event handlers--->You attach event handlers to form elements using JSX syntax such as onChange and onSubmit.
    Event handler functions--->functions receive an event object as an argument. This object contains information about the event, including the element that triggered it and the new value (for onChange).
    State Updates--->When you capture the new value in the event handler, you typically update the component's state using the useState hook.
    Re-rendering--->Whenever the state is updated, React re-renders the component.

3.To prevent this and handle form submission yourself, you can use the event.preventDefault() method.

  1. Utilize controlled components where the form data is controlled by the React component's state. This allows for easy access and manipulation of the data for display.
    Define a state variable within your component using the useState hook to store the form data.
    Attach event handlers (onChange) to the form elements like text fields and checkboxes. Within the event handler, call the state update function you defined earlier, passing the new value as an argument.

  2. we can manage states by using either controlled or uncontrolled forms.
    Control input state: Use useState and bind value to state. Update on change: Make functions to update state with new input value.

@PamelaGwala
Copy link

@ndlovuSimphiwe @pumlanikwena
1)With controlled components,the state of the React component holds the current value of the form element while with uncontrolled components the value of the form element itself holds the current data. You can access this value using refs
2)React forms rely on event handling to capture user interactions and update the form's state accordingly, responding to these events with specific functions called event handlers.
3)In React, you can prevent the default behavior of a form submission using the event.preventDefault() method within the onSubmit event handler for your form.
4)Create a form with controlled components to manage the input values in the state.
Display the current state values below the form.
5)Managing the state of a form input in React typically involves using the useState hook to create state variables for each form field. You then use controlled components, where the input value is derived from the state and updated via event handlers. This approach ensures that the form data is synchronized with the state, providing a reliable way to handle user input.

@Siya-Faith
Copy link

Siyabonga Hlongwane.

  1. Controlled Components
    Controlled components in React are components that do not maintain their own state. Instead, the parent component fully controls the form data. The state of the input elements is managed by React and passed down as props.

Example of Controlled Component:
import React, { useState } from 'react';

function ControlledComponent() {
const [value, setValue] = useState('');

const handleChange = (event) => {
setValue(event.target.value);
};

return (



Current Value: {value}



);
}

export default ControlledComponent;

Uncontrolled Components
Uncontrolled components are components that maintain their own internal state. They use a ref to access the DOM elements directly.

Example of Uncontrolled Component:
import React, { useRef } from 'react';

function UncontrolledComponent() {
const inputRef = useRef();

const handleSubmit = (event) => {
event.preventDefault();
alert(Input Value: ${inputRef.current.value});
};

return (



Submit

);
}

export default UncontrolledComponent;

  1. Event Handling in React Forms
    Event handling in React forms involves using event handlers like onChange, onSubmit, and onClick to manage and respond to user interactions. React uses synthetic events, which are a cross-browser wrapper around the browser’s native event system.

Example of Event Handling:
import React, { useState } from 'react';

function FormEventHandling() {
const [name, setName] = useState('');

const handleChange = (event) => {
setName(event.target.value);
};

const handleSubmit = (event) => {
event.preventDefault();
alert(Form submitted with name: ${name});
};

return (



Submit

);
}

export default FormEventHandling;

  1. Preventing Default Form Submission Behavior
    To prevent the default behavior of form submission in React, you can call event.preventDefault() inside the form's submit handler.

Example:
const handleSubmit = (event) => {
event.preventDefault();
// Add your custom form submission logic here
};

  1. Displaying Form Data in Real-Time
    You can display the data entered into a form in real-time by using state to manage the input values and then rendering those values below the form.

Example:
import React, { useState } from 'react';

function RealTimeFormDisplay() {
const [formData, setFormData] = useState({ name: '', email: '' });

const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};

return (







Entered Data:


Name: {formData.name}


Email: {formData.email}




);
}

export default RealTimeFormDisplay;

  1. Managing Form Input State in React
    Managing form input state in React typically involves using the useState hook to create state variables and updating these variables in the onChange event handler of the input elements.

Example:
import React, { useState } from 'react';

function ManageFormInputState() {
const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {
setInputValue(event.target.value);
};

return (



Current Input: {inputValue}



);
}

export default ManageFormInputState;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment