Browse Courses

Props and Event Handling

This document explains how to use props and event handling in React class components, covering state management, data flow, and user interaction techniques for building dynamic interfaces.

This document explores how React class components use props and event handling to manage state, pass data, and respond to user interactions. It covers class component structure, state management, parent-child data flow, and practical event handling examples for building interactive UIs.


Introduction to Class Components, Props, and Events

React class components are JavaScript classes that extend React.Component. They encapsulate UI logic, manage state, handle lifecycle events, and define methods for user interaction. Before hooks, class components were the primary way to build complex, stateful React UIs.


Structure of a React Class Component

A class component is defined using ES6 class syntax and must include a render method that returns JSX. The component can import React and the base Component class, and is typically exported for use in other files.

Example: Basic Class Component

 1import React, { Component } from 'react'
 2
 3class MyComponent extends Component {
 4  render() {
 5    return (
 6      <div>
 7        <h1>Hello, world!</h1>
 8      </div>
 9    )
10  }
11}
12
13export default MyComponent

State Management in Class Components

State represents the data a component needs to render and respond to user actions. State is initialized in the constructor and updated using this.setState. State changes trigger re-rendering, keeping the UI in sync with user input.

Example: State Management

 1class EmployeeDetails extends Component {
 2  constructor(props) {
 3    super(props)
 4    this.state = {
 5      emp_id: '',
 6      emp_email: ''
 7    }
 8  }
 9
10  handleInputChange = event => {
11    const { name, value } = event.target
12    this.setState({ [name]: value })
13  }
14
15  render() {
16    return (
17      <div>
18        <input
19          name="emp_id"
20          value={this.state.emp_id}
21          onChange={this.handleInputChange}
22        />
23        <input
24          name="emp_email"
25          value={this.state.emp_email}
26          onChange={this.handleInputChange}
27        />
28      </div>
29    )
30  }
31}

Props: Passing Data from Parent to Child

Props (properties) are used to send data from a parent component to a child component. Props are read-only in the child and cannot be modified. They can also be used to pass methods for event handling.

Example: Passing Props

 1// Parent Component
 2;<OrganizationDetails employee_designation="Project Manager" />
 3
 4// Child Component
 5class EmployeeDetails extends Component {
 6  render() {
 7    const { employee_designation } = this.props
 8    return <div>Designation: {employee_designation}</div>
 9  }
10}

Event Handling in Class Components

Event handling in React is the process of responding to user actions such as clicks, mouse events, and form submissions. Event handlers are typically defined as class methods or arrow functions and attached to JSX elements using event attributes like onClick.

Example: Handling Events

 1class EmployeeDetails extends Component {
 2  // ...constructor and state...
 3
 4  showDetails = () => {
 5    const { emp_id, emp_email } = this.state
 6    alert(`ID: ${emp_id}, Email: ${emp_email}`)
 7  }
 8
 9  render() {
10    return <button onClick={this.showDetails}>Show Details</button>
11  }
12}

Combined Example: Props, State, and Event Handling

 1class EmployeeDetails extends Component {
 2  constructor(props) {
 3    super(props)
 4    this.state = {
 5      emp_id: '',
 6      emp_email: ''
 7    }
 8  }
 9
10  handleInputChange = event => {
11    const { name, value } = event.target
12    this.setState({ [name]: value })
13  }
14
15  showDetails = () => {
16    const { emp_id, emp_email } = this.state
17    const { employee_designation } = this.props
18    alert(
19      `ID: ${emp_id}, Email: ${emp_email}, Designation: ${employee_designation}`
20    )
21  }
22
23  render() {
24    const { employee_designation } = this.props
25    return (
26      <div>
27        <input
28          name="emp_id"
29          value={this.state.emp_id}
30          onChange={this.handleInputChange}
31        />
32        <input
33          name="emp_email"
34          value={this.state.emp_email}
35          onChange={this.handleInputChange}
36        />
37        <div>Designation: {employee_designation}</div>
38        <button onClick={this.showDetails}>Show Details</button>
39      </div>
40    )
41  }
42}

Key Differences: State vs Props

FeatureStateProps
MutabilityMutable (can be changed by the component)Immutable (read-only in child)
ScopeLocal to the componentPassed from parent to child
UsageManages internal data and UI updatesPasses data and methods to children

Conclusion

React class components use state to manage internal data, props to receive data from parents, and event handlers to respond to user actions. Mastering these concepts enables the creation of dynamic, interactive, and maintainable user interfaces.


FAQ

  1. Props allow data to be passed from parent to child components and are read-only in the child.
  2. Props are used to manage internal state within a component.
  3. Props handle all event logic in React.
  4. Props are only used for styling components.
(1) Props allow data to be passed from parent to child components and are read-only in the child.

The component’s state will update, triggering a re-render so the UI reflects the new value entered by the user.

  1. Event handlers can be defined as arrow functions or class methods.
  2. Event handlers are attached to JSX elements using event attributes like onClick.
  3. Event handlers can directly mutate props.
  4. Event handlers can access and update component state.
(3) Event handlers cannot directly mutate props; props are read-only in the child component.

State is mutable and managed within the component, while props are immutable and passed from parent to child for data sharing.

Event handlers enable components to respond to user interactions, such as clicks and input changes, making the UI dynamic and interactive.

ConceptDescription
A. State1. Passes data from parent to child
B. Props2. Handles user actions like clicks
C. Event3. Manages internal data and UI updates
A-3, B-1, C-2.

Making props read-only ensures predictable data flow and prevents accidental modification of parent data by child components.

A parent can pass data and methods to a child via props, enabling the child to display information and trigger actions in the parent.

Ensure that state is being updated correctly and that props are being passed and used properly in the component.

In React, event handlers can update component state, which triggers a re-render of the component.

True. Updating state in an event handler causes the component to re-render with the new data.