ganesh kaspate
ganesh kaspate

Reputation: 2685

How do I Bind the function instead of creating a new one?

I am new to react. here I have a functional component. In which I have

const bginfo = useLocalStore(() => ({
      status: bgStatus,
      setStatus(val) {
        bginfo.status = val;
      }
    }));
return (
  <div className={css.root}>
    <Select
      onChange={(event) => bginfo.setStatus(event.target.value)}
      value={bginfo.status}
      id="bgStatus"
    />

SO, In this , Now instead of creating new instance I want to bind function here instead of creating new instance.

How do I do this ? Can any one help me with this ?.

Upvotes: 0

Views: 52

Answers (1)

Andus
Andus

Reputation: 1731

Create a new function and pass to onChange, it automatically have the event passed if you use it with onChange/onClick

setStatus = (event) => {
  bginfo.setStatus(event.target.value);
}

<Select
  onChange={setStatus}
  value={bginfo.status}
  id="bgStatus"
/>

Here's an official example from the React docs

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Upvotes: 1

Related Questions