Class components: React class and class components; conditional statements, operators, lists; React Events (adding events, passing arguments, event objects)

React components react कर सकते हैं: onClick से events handle कीजिए, map से lists render कीजिए (हर एक को एक key चाहिए), और && और ternary operator इस्तेमाल करके conditional rendering से content show या hide कीजिए।

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

एक UI जो कुछ नहीं करती, वह UI नहीं है

पिछले lesson के FestConnect components events display करते हैं पर inertly बैठे रहते हैं। एक real interface RESPOND करता है: इसे select करने के लिए एक card click करना, seats zero होने पर 'Sold out' देखना, एक array से पूरी list render करना।

यह lesson components को react कराता है: events (clicks handle करना), lists (events के एक array को render करना), और conditional rendering (सिर्फ़ appropriate होने पर 'Sold out' दिखाना)। यह React की class-component style इस्तेमाल करता है, जो आपका syllabus modern function-and-hooks style के साथ सिखाता है (बाद में आ रही)। Concepts, events, lists, conditionals, दोनों styles में same हैं।

Theory

Events Handle करना

React user actions को camelCase event handlers से handle करता है जो एक FUNCTION लेते हैं:

<button onClick={handleClick}>Register</button>

नोट कीजिए onClick={handleClick}: आप function का NAME pass करते हैं (एक reference), handleClick() नहीं (जो इसे render पर तुरंत CALL कर देता)। एक ARGUMENT pass करने के लिए, इसे एक arrow function में wrap कीजिए:

<button onClick={() => handleClick(eventId)}>Register</button>

Handler को एक event object मिलता है (conventionally e) जो e.target जैसे details carry करता है। यह BCA405-01 के DOM वाला same event idea है, React के syntax में wrapped। Immediate-call bug (onClick={handleClick(id)}) सबसे common React event mistake है।

Practical

Keys, Events, और Conditional Rendering वाली List

function EventList() {
  const events = [
    { id: 1, name: "Garba Night", seats: 350 },
    { id: 2, name: "Coding Contest", seats: 0 },
  ];

  function handleClick(name) {
    alert("Selected: " + name);
  }

  return (
    <ul>
      {events.map((ev) => (
        <li key={ev.id}>                        {/* each item needs a KEY */}
          {ev.name} -
          {/* conditional rendering with a ternary */}
          {ev.seats > 0
            ? <span> {ev.seats} seats</span>
            : <span> Sold out</span>}
          {/* arrow wrapper to pass an argument */}
          <button onClick={() => handleClick(ev.name)}>Select</button>
        </li>
      ))}
    </ul>
  );
}

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

Lists और Conditional Rendering

Lists: .map() call करके एक array render कीजिए, हर item के लिए JSX return करते हुए। हर rendered item को एक unique `key` prop चाहिए (key={ev.id}): React keys इस्तेमाल करता है ट्रैक करने के लिए कौन से items बदले, ताकि यह efficiently update कर सके। एक missing key एक warning produce करता है और subtle bugs cause कर सकता है; जहाँ possible हो array index नहीं, एक stable unique id इस्तेमाल कीजिए।

Conditional rendering: एक condition के based पर content दिखाइए, इस्तेमाल करते हुए:

  • ternary: condition ? <A/> : <B/> (A या B दिखाता है)
  • logical AND: condition && <A/> (सिर्फ़ तब A दिखाता है जब condition true हो)

तो ev.seats > 0 ? <span>{ev.seats} seats</span> : <span>Sold out</span> seat count या 'Sold out' दिखाता है। ये JSX के {} के अंदर इस्तेमाल होने वाले ordinary JavaScript operators हैं।

Quiz

आप id को handler को pass करने के लिए <button onClick={handleClick(id)}>Go</button> लिखते हैं। actually क्या होता है?

  1. यह correctly button click होने पर handleClick(id) call करता है
  2. handleClick(id) IMMEDIATELY call होता है जब component render होता है, click पर नहीं; आपको एक arrow wrapper चाहिए onClick={() => handleClick(id)}
  3. यह एक syntax error throw करता है
  4. id ignore हो जाती है
Show the answer

handleClick(id) IMMEDIATELY call होता है जब component render होता है, click पर नहीं; आपको एक arrow wrapper चाहिए onClick={() => handleClick(id)}

onClick={handleClick(id)} render के दौरान handleClick(id) तुरंत CALL करता है (इसकी RETURN value click handler बन जाती है), तो यह तुरंत fire होता है, click पर नहीं: एक classic React bug। Click पर एक argument pass करने के लिए, इसे एक arrow function में wrap कीजिए: onClick={() => handleClick(id)}, जो onClick को एक FUNCTION देता है जो सिर्फ़ click होने पर handleClick(id) call करता है। Option A वह है जो आपने INTEND किया था पर यह code वह नहीं करता। Option C ग़लत है: यह valid syntax है, बस ग़लत behaviour (जो इसे insidious बनाता है)। Option D miss करता है कि पूरी call जल्दी चलती है। Rule: onClick को एक function reference चाहिए; arguments pass करने के लिए, एक arrow wrapper इस्तेमाल कीजिए।

Think first

हर List Item को Key क्यों चाहिए?

अगर आप बिना key prop के एक list को JSX में map करते हैं तो React warn करता है। Key क्या करती है, और यह performance और correctness के लिए क्यों matter करती है? फिर tap कीजिए।

Show the answer

KEY हर list item को एक stable IDENTITY देती है ताकि React इसे re-renders के across track कर सके। जब list बदलती है (एक item add, remove, या reorder होता है), React नई list को पुरानी से KEY से compare करता है यह figure out करने के लिए MINIMAL update क्या है: कौन से items रखें, move करें, या replace करें, सब कुछ rebuild करने की बजाय। बिना keys के, React position पर fall back करता है, जो इसे WRONG items update करने cause कर सकता है (जैसे एक input का text ग़लत row से चिपकना) और ज़रूरत से ज़्यादा काम करना। एक STABLE UNIQUE id (ev.id जैसा) इस्तेमाल कीजिए, array index नहीं, क्योंकि items add/remove होने पर indexes shift होते हैं। Key user को नहीं दिखाई जाती; यह हर item पर React का internal handle है। Missing या unstable keys दोनों warning AND real, confusing bugs cause करती हैं।

Watch out

Events, Lists, Conditionals Traps

Immediate-Call Handler: onClick={fn(arg)} अभी चलता है; onClick={() => fn(arg)} इस्तेमाल कीजिए।

Mapped Items पर Missing Key: एक warning और update bugs cause करता है; एक stable unique id इस्तेमाल कीजिए।

Items Reorder होने पर Array Index को Key की तरह इस्तेमाल करना: indexes shift होते हैं; एक real id prefer कीजिए।

= और => Confuse करना: handlers एक function pass करते हैं, अक्सर एक arrow।

JSX में JS के आस-पास {} भूलना: conditionals और map curly braces के अंदर जाते हैं।

Theory

यह React करता है; अब Input Capture कीजिए

FestConnect की list अब clicks respond करती है, keys के साथ एक array से render होती है, और conditionally 'Sold out' दिखाती है। अगला बड़ा interaction INPUT है: forms जहाँ users अपने registration details type करते हैं। React forms को एक specific तरीके से handle करता है, controlled components, जहाँ form का data component में रहता है और हर keystroke इसे update करता है। Forms, controlled inputs, और select/textarea आगे आते हैं, फिर hooks modern React picture complete करते हैं।

Summary

Key takeaways

  • React components users को react करते हैं; class components (render() के साथ React.Component extend करते हुए) older style है, function components + hooks के साथ।
  • Events camelCase handlers इस्तेमाल करते हैं जो एक function लेते हैं: onClick={handleClick}; handler को एक event object (e) मिलता है।
  • एक argument pass करने के लिए, एक arrow wrapper इस्तेमाल कीजिए: onClick={() => handleClick(id)}; onClick={handleClick(id)} इसे तुरंत call करता है (bug)।
  • Lists को .map() से render कीजिए हर item के लिए JSX return करते हुए; हर एक को एक unique key prop चाहिए (index नहीं, एक stable id इस्तेमाल कीजिए)।
  • Keys items को identity देती हैं ताकि React efficiently और correctly update करे।
  • Conditional rendering: ternary (cond ? <A/> : <B/>) या logical AND (cond && <A/>)।
  • Memory hook: arguments के लिए arrow-wrap कीजिए, हर list item को key दीजिए, conditionals के लिए ternary/&&।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Fundamentals of React.js

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati