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?
@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