msmith1114
msmith1114

Reputation: 3231

React: Passing parameters in Dumb Component Functions

So I am in the process of working on a sort of "intermediate" level react project. I know the basics, but don't know best practices on some things.

Lets pretend I am passing a function to a "Dumb" component, in this dumb component is a button that is a callback to a parent function Editname which looks like this:

editName = (id) => {
    console.log(`Name edited for ${id}`);
}

In the "Dumb" component there is a button that calls this since it's being passed as a prop from it's parent:

<button type="input" onClick={props.editName}>Edit</button>

However the problem is, I need to pass along the id as well to the callback function (I get the id as a prop in the dumb component as well). What's the best way to go about this? I know one option is:

{()=> {props.editName(props.id)} but i've been told this is a bad practice because the function will get created everytime. So what is the "proper" way to do this? Or do I need to make it as a class and handle it as a callback to another function within the class?

Upvotes: 0

Views: 344

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 17

For good practice you should use destructuring in your code like...

const { editName, id } = props;
<button type="input" onClick={editName} data-id={id}>Edit</button>

For destructuring practices folllow this link.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Upvotes: 1

Anand Undavia
Anand Undavia

Reputation: 3543

To avoid creating the function everytime, you can attach an identifier to the target element using data-* attributes and then make use of it further.

For example:

<button type="input" onClick={props.editName} data-id="edit-button">Edit</button>

And then, in the function, you can have this:

editName = event => {
  const id = event.target.getAttribute("data-id");
  console.log(`Name edited for ${id}`);
};

You can very well take the data-id from the props:

<button type="input" onClick={props.editName} data-id={props.id}>Edit</button>

How you would want to manage the data-id attribute will depend upon the use case.


This might not be the proper way, as OP has asked, but it does reduce the number of functions created everytime.

Upvotes: 1

Related Questions