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>
);
}
CodePudding user response:
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.
- Use props.property
const IncrementButton = (props) => {
return (
<button onClick={props.handleClick}> </button>
)
}
- Destructure the props object
const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}> </button>
)
}
CodePudding user response:
You didn't destructure handle click. Try the code below
const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}> </button>
)
}
CodePudding user response:
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.
- Destructure props (
es6
)
const IncrementButton = ({handleClick}) => {
return (
<button onClick={handleClick}> </button>
)
}
- Use
props.propertyName
const IncrementButton = (props) => {
return (
<button onClick={props.handleClick}> </button>
)
}