Reputation: 717
I wonder if there is a way to pass values to a function such as "onClick". The following code is not to be considered due to performance considerations:
<div onClick={() => handleClick(value)}/>
I'd like to write:
<div onClick={handleClick(value)}/>
But this ain't possible in React. Any solutions?
Upvotes: 2
Views: 3747
Reputation: 1961
Yes, if your callback of a prop such as: onClick
will pass a param event when it call. In this case, just pass a function name. Example:
const Comp = (props) => {
const [value, setValue] = useState(0);
const handleClick = (event) => {
setValue(value + 1);
}
return <div>
<div> {value} </div>
{/*pass function name that declare of function have one param or don't have any pram*/}
<button onClick={handleClick} > Click me</button>
</div>
}
Upvotes: 0
Reputation: 454
actually it is possible: you need to return a function that do your work. something like this:
const handleClick = value => () => {
// your logic
}
then use it like this:
<div onClick={handleClick(value)}/>
Upvotes: 4