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