Reputation: 5223
I have made my first component. The goal is to create a simple dropdown. Every time I add a parameter the click event is fired infinitely:
onClick={dropDownChanged(10)}
If I call it like below then the event is fired when clicked, but then I don't get the value needed:
onClick={dropDownChanged}
How do I pass my value so I can update the dropdown with the selected value? I also tried not using an arrow function, but same behaviour.
import React, { useState } from "react";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
Button
} from "reactstrap";
const DropdownPaging = props => {
const [dropdownOpen, setDropdownOpen] = useState(false);
const toggle = () => setDropdownOpen(prevState => !prevState);
const dropDownChanged = val => {
alert("ff");
};
return (
<div>
<table>
<tr>
<td>
<Button outline color="dark">
<
</Button>
</td>
<td>
<Button outline color="dark">
>
</Button>
</td>
<td>
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret outline color="dark">
10
</DropdownToggle>
<DropdownMenu>
<DropdownItem onClick={dropDownChanged}>10</DropdownItem>
<DropdownItem onClick={dropDownChanged}>25</DropdownItem>
<DropdownItem onClick={dropDownChanged}>50</DropdownItem>
<DropdownItem onClick={dropDownChanged}>100</DropdownItem>
</DropdownMenu>
</Dropdown>
</td>
</tr>
</table>
</div>
);
};
export default DropdownPaging;
Upvotes: 1
Views: 316
Reputation: 563
There is a difference between giving it as
onClick={ dropDownChanged(10) }
and
onClick={ dropDownChanged }
In case 1: The code invokes the function as soon as that part of code is ran. ie. When the component is rendered, the function is automatically invoked, which leads to unexpected behaviours.
In case 2: The function is being passed as reference. This is correct way os passing a function to a click handler but it will be invoked when the button is clicked. But the problem with this approach is that we can not send the value when we invoke the function.
The ideal solution in this usecase is to pass a callback function to the event handler.
ie. onClick={() => dropDownChanged(10)}
When the button is clicked, it inturn invokes the callback function and works as expected. Hope this clarifies the behavior of event handlers !
Upvotes: 1
Reputation: 525
Pass the function in like this
onClick={() => dropDownChanged(10)}
Upvotes: 0