2

I have a basic increment app in react with the following code. Passing in the handleClick function into the first button works fine, however passing it to a child component IcrementButton that returns the exact same button gives the error: React: Expected `onClick` listener to be a function, instead got a value of `object. Why is it working for the first button but not the child component button and how can it be fixed? thanks in advance.

import { useState } from "react";
import "./styles.css";

const IncrementButton = (handleClick) => {
  return (
    <button onClick={handleClick}>+</button>
  )
}

export default function App() {
  const [num, setNum] = useState(0)
  const handleClick = (e) => {
    e.preventDefault()
    console.log('clicked')
    setNum(prev => prev += 1)
  }
  return (
    <div className="App">
      <div>{num}</div>
      <button onClick={handleClick}>+</button>
      <IncrementButton handleClick={handleClick} />
    </div>
  );
}
1
  • Typo, you neglected to destructure the handleClick callback from the props object. Voted to close as "Not reproducible or was caused by a typo". Cheers. Commented Feb 25, 2022 at 8:04

3 Answers 3

7

Since the IncrementButton is a custom component all props passed to it is sent as an object and to access it you need to use props.property. There are 2 ways to get your code to work.

  1. Use props.property
const IncrementButton = (props) => {
  return (
    <button onClick={props.handleClick}>+</button>
  )
}
  1. Destructure the props object
const IncrementButton = ({handleClick}) => {
  return (
    <button onClick={handleClick}>+</button>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

2

You didn't destructure handle click. Try the code below

const IncrementButton = ({handleClick}) => {
  return (
    <button onClick={handleClick}>+</button>
  )
}

Comments

2

That does not work because React passes every props on a Component as a single Object.

You have two ways to get handleClick function reference.

  1. Destructure props (es6)
const IncrementButton = ({handleClick}) => {
  return (
    <button onClick={handleClick}>+</button>
  )
}
  1. Use props.propertyName
const IncrementButton = (props) => {
  return (
    <button onClick={props.handleClick}>+</button>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.