Bird
Raised Fist0
Reactframework~20 mins

Handling events in React - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
React Event Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What happens when the button is clicked?
Consider this React component. What will be the displayed text after clicking the button once?
React
import React, { useState } from 'react';

function ClickCounter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default ClickCounter;
AThe button click causes a syntax error.
BThe text remains 'You clicked 0 times'.
CThe text changes to 'You clicked 1 times'.
DThe text changes to 'You clicked NaN times'.
Attempts:
2 left
💡 Hint
Think about how useState updates the count when the button is clicked.
📝 Syntax
intermediate
1:00remaining
Which option correctly attaches an event handler in React?
You want to run a function named handleClick when a button is clicked. Which JSX syntax is correct?
A<button onClick={handleClick}>Click</button>
B<button onClick={handleClick()}>Click</button>
C<button onclick={handleClick}>Click</button>
D<button OnClick={handleClick}>Click</button>
Attempts:
2 left
💡 Hint
React event handlers are camelCase and expect a function reference, not a function call.
🔧 Debug
advanced
2:00remaining
Why does this event handler cause an error?
This React component throws an error when clicking the button. What is the cause?
React
import React from 'react';

function MyButton() {
  function handleClick() {
    console.log(this);
  }
  return <button onClick={handleClick}>Click me</button>;
}

export default MyButton;
AThe component is missing a return statement.
B'this' is undefined inside handleClick because it is a regular function, not bound to the component.
ChandleClick is called immediately instead of on click, causing an error.
DThe onClick attribute is misspelled causing the handler not to run.
Attempts:
2 left
💡 Hint
Consider how 'this' behaves in JavaScript functions inside React components.
❓ state_output
advanced
2:00remaining
What is the output after clicking the button twice quickly?
Examine this React component. What will be the final count displayed after clicking the button twice quickly?
React
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  function increment() {
    setCount(count + 1);
    setCount(count + 1);
  }
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;
ACount will be 1 after two quick clicks.
BCount will be 2 after two quick clicks.
CCount will be 4 after two quick clicks.
DCount will be 0 after two quick clicks.
Attempts:
2 left
💡 Hint
Think about how React batches state updates and the value of 'count' inside increment.
🧠 Conceptual
expert
2:30remaining
Why use event delegation in React event handling?
React uses a synthetic event system that attaches a single event listener at the root. What is the main benefit of this event delegation approach?
AIt disables event bubbling to avoid unwanted side effects.
BIt allows direct access to native DOM events without any abstraction.
CIt forces all events to be handled synchronously, preventing delays.
DIt improves performance by reducing the number of event listeners attached to DOM nodes.
Attempts:
2 left
💡 Hint
Think about how many event listeners would be needed if each element had its own listener.

Practice

(1/5)
1. In React, how do you correctly attach a click event handler to a button?
easy
A. <button onclick="handleClick()">Click me</button>
B. <button onClick={handleClick}>Click me</button>
C. <button OnClick={handleClick}>Click me</button>
D. <button onClick="handleClick()">Click me</button>

Solution

  1. Step 1: Understand React event naming

    React uses camelCase for event handlers, so onClick is correct, not lowercase or capitalized differently.
  2. Step 2: Attach event handler as a function reference

    In React, event handlers are passed as functions, not strings. So {handleClick} is correct, not a string like "handleClick()".
  3. Final Answer:

    <button onClick={handleClick}>Click me</button> -> Option B
  4. Quick Check:

    React event handler syntax = <button onClick={handleClick}>Click me</button> [OK]
Hint: Use camelCase and pass function, not string, for events [OK]
Common Mistakes:
  • Using lowercase event names like onclick
  • Passing event handler as a string instead of function
  • Capitalizing event names incorrectly
2. Which of the following is the correct syntax to define an event handler function inside a React functional component?
easy
A. const handleClick = () => console.log('Clicked');
B. handleClick = () => console.log('Clicked');
C. handleClick() => { console.log('Clicked'); }
D. def handleClick() { console.log('Clicked'); }

Solution

  1. Step 1: Recognize JavaScript function syntax in React

    React functional components use JavaScript, preferring arrow functions declared with const for event handlers.
  2. Step 2: Identify correct arrow function syntax

    const handleClick = () => console.log('Clicked'); is correct. Other options have syntax errors such as missing variable declaration or invalid syntax.
  3. Final Answer:

    const handleClick = () => console.log('Clicked'); -> Option A
  4. Quick Check:

    Arrow function syntax = const handleClick = () => console.log('Clicked'); [OK]
Hint: Use arrow functions for event handlers inside components [OK]
Common Mistakes:
  • Using invalid function syntax like 'handleClick() => {}'
  • Using Python syntax 'def' in JavaScript
  • Not assigning function to a variable
3. What will be the output when the button is clicked in this React component?
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => setCount(count + 1);
  return (
    <button onClick={handleClick}>Clicked {count} times</button>
  );
}
medium
A. Button shows 'Clicked 0 times' initially and increments on each click
B. Button shows 'Clicked 1 times' initially and increments on click
C. Button shows 'Clicked 0 times' and never changes
D. Button causes a runtime error on click

Solution

  1. Step 1: Understand useState initial value

    The state variable count starts at 0, so the button initially shows 'Clicked 0 times'.
  2. Step 2: Analyze handleClick behavior

    Each click calls handleClick, which updates count by adding 1, so the displayed count increments on each click.
  3. Final Answer:

    Button shows 'Clicked 0 times' initially and increments on each click -> Option A
  4. Quick Check:

    useState increments count on click = Button shows 'Clicked 0 times' initially and increments on each click [OK]
Hint: useState updates UI on event, so count increments on clicks [OK]
Common Mistakes:
  • Thinking state does not update on click
  • Confusing initial state with updated state
  • Expecting runtime errors from correct code
4. Identify the error in this React event handler code:
function MyButton() {
  const handleClick = () => {
    console.log('Clicked');
  }
  return <button onclick={handleClick}>Click me</button>;
}
medium
A. Missing parentheses when calling handleClick
B. Button element must be self-closing
C. Incorrect event name 'onclick' should be 'onClick'
D. handleClick function is not defined

Solution

  1. Step 1: Check event handler attribute name

    React requires camelCase event names, so onclick is incorrect; it should be onClick.
  2. Step 2: Verify function definition and usage

    The function handleClick is correctly defined and passed as a reference, so no error there.
  3. Final Answer:

    Incorrect event name 'onclick' should be 'onClick' -> Option C
  4. Quick Check:

    React event names are camelCase = Incorrect event name 'onclick' should be 'onClick' [OK]
Hint: React event names use camelCase, not lowercase [OK]
Common Mistakes:
  • Using lowercase event names
  • Forgetting to pass function reference
  • Misunderstanding JSX syntax for elements
5. You want to create a React component that increments a counter only when the user presses the Enter key inside an input box. Which is the correct way to handle this event?
function EnterCounter() {
  const [count, setCount] = React.useState(0);
  const handleKeyDown = (event) => {
    // What condition should be here?
  };
  return (
    <>
      <input type="text" onKeyDown={handleKeyDown} aria-label="Enter key counter input" />
      <p>Count: {count}</p>
    </>
  );
}
hard
A. if (event.which === 'Enter') setCount(count + 1);
B. if (event.keyCode === 13) setCount(count + 1);
C. if (event.key === 13) setCount(count + 1);
D. if (event.key === 'Enter') setCount(count + 1);

Solution

  1. Step 1: Identify the correct property for key detection

    Modern React and browsers use event.key as a string to detect keys, so checking event.key === 'Enter' is correct.
  2. Step 2: Understand deprecated properties

    event.keyCode and event.which are deprecated or inconsistent; also, comparing event.key to a number like 13 is incorrect.
  3. Final Answer:

    if (event.key === 'Enter') setCount(count + 1); -> Option D
  4. Quick Check:

    Use event.key string for key detection = if (event.key === 'Enter') setCount(count + 1); [OK]
Hint: Use event.key === 'Enter' to detect Enter key presses [OK]
Common Mistakes:
  • Using deprecated event.keyCode or event.which
  • Comparing event.key to a number instead of string
  • Not checking key inside keydown event
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard