Embedded_Mugs
Embedded_Mugs

Reputation: 2426

React: Expected `onClick` listener to be a function, instead got a value of `object` type but only when I pass it to a child component

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>
  );
}

Upvotes: 2

Views: 8318

Answers (3)

Neyaz Ahmad
Neyaz Ahmad

Reputation: 174

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>
  )
}

Upvotes: 2

Aaditey Nair
Aaditey Nair

Reputation: 363

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>
  )
}

Upvotes: 7

Nekan123
Nekan123

Reputation: 72

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

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

Upvotes: 2

Related Questions