Reputation: 2426
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
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.
es6
)const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}>+</button>
)
}
props.propertyName
const IncrementButton = (props) => {
return (
<button onClick={props.handleClick}>+</button>
)
}
Upvotes: 2
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.
const IncrementButton = (props) => {
return (
<button onClick={props.handleClick}>+</button>
)
}
const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}>+</button>
)
}
Upvotes: 7
Reputation: 72
You didn't destructure handle click. Try the code below
const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}>+</button>
)
}
Upvotes: 2