React.js – Props, State & Event Handling

4. Props – Greeting Card

Props (properties) are how we pass data from parent to child components. Think of them as function parameters.

GreetingCard Component

GreetingCard.js

import React from 'react';                           // Line 1: Import React library

function GreetingCard({ name, message, color }) {    // Line 2: Component receives props as parameters
  return (                                          // Line 3: Return JSX structure
    <div className="greeting-card">                 // Line 4: Main card container
      <div                                          // Line 5: Inner card div with dynamic styling
        className="card-content"                    // Line 6: CSS class for styling
        style={{ backgroundColor: color }}          // Line 7: Inline style using color prop
      >                                             // Line 8: Close opening div tag
        <h2>Hello, {name}!</h2>                    // Line 9: Display name prop in heading
        <p className="message">{message}</p>        // Line 10: Display message prop in paragraph
        <div className="card-footer">              // Line 11: Footer section
          <small>From: Your React App</small>      // Line 12: Static footer text
        </div>                                     // Line 13: Close footer
      </div>                                       // Line 14: Close inner card div
    </div>                                         // Line 15: Close main container
  );                                               // Line 16: Close return statement
}                                                  // Line 17: Close function

export default GreetingCard;                       // Line 18: Export for use in other files

Using GreetingCard in App.js

App.js

import React from 'react';                         // Line 1: Import React
import GreetingCard from './GreetingCard';         // Line 2: Import our GreetingCard component

function App() {                                   // Line 3: Main App component
  return (                                         // Line 4: Return JSX
    <div className="app">                          // Line 5: App container
      <h1>My Greeting Cards</h1>                   // Line 6: App title
      
      <GreetingCard                                // Line 7: First greeting card
        name="Alice"                               // Line 8: Pass name as prop
        message="Hope you have a wonderful day!"   // Line 9: Pass message as prop
        color="#ffcccb"                           // Line 10: Pass color as prop (light red)
      />                                          // Line 11: Close first card
      
      <GreetingCard                               // Line 12: Second greeting card
        name="Bob"                                // Line 13: Different name prop
        message="Happy coding with React!"        // Line 14: Different message prop
        color="#add8e6"                          // Line 15: Different color prop (light blue)
      />                                          // Line 16: Close second card
    </div>                                        // Line 17: Close app container
  );                                              // Line 18: Close return
}                                                 // Line 19: Close App function

export default App;                               // Line 20: Export App component

Key Props Concepts:

  • Props flow down from parent to child
  • Props are read-only (immutable)
  • Use curly braces {} for JavaScript expressions
  • Props make components reusable with different data

5. State – Counter App

State is data that belongs to a component and can change over time. When state changes, the component re-renders.

Counter Component with useState

Counter.js

import React, { useState } from 'react';           // Line 1: Import React and useState hook

function Counter() {                               // Line 2: Counter component function
  const [count, setCount] = useState(0);           // Line 3: Declare state variable 'count' with initial value 0
  
  const increment = () => {                        // Line 4: Function to increase count
    setCount(count + 1);                          // Line 5: Update count by adding 1
  };                                              // Line 6: Close increment function
  
  const decrement = () => {                        // Line 7: Function to decrease count
    setCount(count - 1);                          // Line 8: Update count by subtracting 1
  };                                              // Line 9: Close decrement function
  
  const reset = () => {                           // Line 10: Function to reset counter
    setCount(0);                                  // Line 11: Set count back to 0
  };                                              // Line 12: Close reset function

  return (                                        // Line 13: Return JSX
    <div className="counter-app">                 // Line 14: Main counter container
      <h2>Counter App</h2>                        // Line 15: App title
      <div className="counter-display">           // Line 16: Display area
        <h1 className="count-number">{count}</h1> // Line 17: Show current count value
      </div>                                      // Line 18: Close display area
      <div className="counter-buttons">           // Line 19: Buttons container
        <button onClick={decrement}>-</button>    // Line 20: Decrement button with click handler
        <button onClick={reset}>Reset</button>    // Line 21: Reset button with click handler
        <button onClick={increment}>+</button>    // Line 22: Increment button with click handler
      </div>                                      // Line 23: Close buttons container
    </div>                                        // Line 24: Close main container
  );                                              // Line 25: Close return
}                                                 // Line 26: Close function

export default Counter;                           // Line 27: Export component

useState Breakdown:

  • useState(0) returns an array: [currentValue, setterFunction]
  • count is the current state value
  • setCount is the function to update the state
  • When setCount is called, component re-renders with new value

6. Event Handling – Click Me Button

Event handling lets us respond to user interactions like clicks, form submissions, etc.

ClickMeButton Component

ClickMeButton.js

import React, { useState } from 'react';           // Line 1: Import React and useState

function ClickMeButton() {                         // Line 2: Component function
  const [buttonText, setButtonText] = useState('Click Me!'); // Line 3: State for button text
  const [buttonColor, setButtonColor] = useState('#3498db'); // Line 4: State for button color
  const [clickCount, setClickCount] = useState(0);  // Line 5: State to track clicks
  
  const handleClick = () => {                      // Line 6: Click event handler function
    setClickCount(clickCount + 1);                 // Line 7: Increment click count
    
    if (clickCount === 0) {                        // Line 8: First click condition
      setButtonText('Clicked!');                   // Line 9: Change text after first click
      setButtonColor('#e74c3c');                   // Line 10: Change to red color
    } else if (clickCount === 1) {                 // Line 11: Second click condition
      setButtonText('Clicked Again!');             // Line 12: Different text for second click
      setButtonColor('#f39c12');                   // Line 13: Change to orange color
    } else {                                       // Line 14: Multiple clicks condition
      setButtonText(`Clicked ${clickCount + 1} times!`); // Line 15: Show click count
      setButtonColor('#9b59b6');                   // Line 16: Change to purple color
    }                                              // Line 17: Close else condition
  };                                               // Line 18: Close handleClick function
  
  const resetButton = () => {                      // Line 19: Reset function
    setButtonText('Click Me!');                    // Line 20: Reset text
    setButtonColor('#3498db');                     // Line 21: Reset color to blue
    setClickCount(0);                              // Line 22: Reset click count
  };                                               // Line 23: Close reset function

  return (                                         // Line 24: Return JSX
    <div className="click-me-app">                 // Line 25: Main container
      <h2>Interactive Button Demo</h2>             // Line 26: App title
      <div className="button-container">           // Line 27: Button wrapper
        <button                                    // Line 28: Main interactive button
          onClick={handleClick}                    // Line 29: Attach click event handler
          style={{                                 // Line 30: Inline styles object
            backgroundColor: buttonColor,          // Line 31: Dynamic background color
            color: 'white',                        // Line 32: Text color
            padding: '15px 30px',                  // Line 33: Button padding
            fontSize: '18px',                      // Line 34: Font size
            border: 'none',                        // Line 35: Remove border
            borderRadius: '8px',                   // Line 36: Rounded corners
            cursor: 'pointer'                      // Line 37: Pointer cursor on hover
          }}                                       // Line 38: Close style object
        >                                          // Line 39: Close button opening tag
          {buttonText}                             // Line 40: Display dynamic button text
        </button>                                  // Line 41: Close button
        
        <button                                    // Line 42: Reset button
          onClick={resetButton}                    // Line 43: Attach reset handler
          className="reset-btn"                    // Line 44: CSS class for styling
        >                                          // Line 45: Close reset button opening tag
          Reset                                    // Line 46: Reset button text
        </button>                                  // Line 47: Close reset button
      </div>                                       // Line 48: Close button container
      
      <p>Total clicks: {clickCount}</p>            // Line 49: Display click counter
    </div>                                         // Line 50: Close main container
  );                                               // Line 51: Close return
}                                                  // Line 52: Close component function

export default ClickMeButton;                     // Line 53: Export component

Key Event Handling Concepts:

Event Handler Functions:

  • Functions that run when events occur
  • Named with handle prefix (e.g., handleClick)
  • Passed to JSX elements via props like onClick

Common Events:

  • onClick – Mouse clicks
  • onChange – Input changes
  • onSubmit – Form submissions
  • onMouseEnter – Mouse hover

Event Handler Best Practices:

  • Define handlers inside component or as separate functions
  • Use arrow functions to avoid this binding issues
  • Keep handlers simple – extract complex logic to separate functions

Using All Three Components Together

App.js

import React from 'react';
import GreetingCard from './GreetingCard';
import Counter from './Counter';
import ClickMeButton from './ClickMeButton';

function App() {
  return (
    <div className="app">
      <h1>React Fundamentals Demo</h1>
      
      <section>
        <h2>Props Example</h2>
        <GreetingCard name="Developer" message="Keep learning!" color="#98fb98" />
      </section>
      
      <section>
        <h2>State Example</h2>
        <Counter />
      </section>
      
      <section>
        <h2>Event Handling Example</h2>
        <ClickMeButton />
      </section>
    </div>
  );
}

export default App;

This demonstrates the three fundamental React concepts working together: Props for data passing, State for dynamic data management, and Event Handling for user interactions.

Leave a Reply

Your email address will not be published. Required fields are marked *