Search code examples
javascriptreactjsstyled-components

Button in table column doesn't wait for the onClick event


I've got a table where last column should work as a "delete item" button. Table looks something like this:

const columns = ({ onClick }) => [
  {
    key: 'type',
    onRender: (item) => (
      <p className="ms-font-m mb-0">
        {item.type}
      </p>
    ),
  },
  {
    key: 'remove',
    onRender: (item) => (
      <PrimaryButton onClick={onClick(item.type)}>
        <FormattedMessage {...messages.removeLight}/>
      </PrimaryButton>
    ),

  },
]

const Table = ({ data, onClick, intl}) => (
  <Table
    items={data}
    compact
    columns={columns({ onClick })}
  />
);

, where the onClick event calls function that rewrites current state and sets the new one, like this:

handleRemove = (type) => {
    const { form } = this.state

    var itemsNew = form.items.filter(e => e.type !== type),

    this.setState({
      form: itemsNew,
    });
  }

Problem is, that when the table is rendered the handleRemove function is called immediately and doesn't wait for the click event. However, if i remove the item.type parameter and call handleRemove as an empty function with some console.log(...) line only, it works just fine.

I am very new to JS and really don't get what am i missing here.


Solution

  • Just change this line <PrimaryButton onClick={onClick(item.type)}> to <PrimaryButton onClick={() => onClick(item.type)}>

    Another solution is to change function 'shape' from this handleRemove = (type) => {...} to this handleRemove = (type) => () => {...}