Search code examples
reactjsreactstrap

onClick event fires infinite when passing a parameter


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">
              &lt;
            </Button>
          </td>
          <td>
            <Button outline color="dark">
              &gt;
            </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;

Solution

  • Pass the function in like this

    onClick={() => dropDownChanged(10)}