skip to Main Content

I’m trying to create a set of buttons generated by React that pull IDs, labels, and links from an array. IDs and labels, through className and .label, both work. I don’t want to use href: for the links – rather, I’d like to call a function (using onClick) that assembles the link using a parameter passed into the .createElement(). Unfortunately, when react renders any elements with a function with paranthesis, it calls the function constantly. Is there any way to pass arguments into functions called by onClick within a .createElement? I Don’t want to use JSX – I’m commited to .createElement for this particular project.

Dummy code for the .createElement():

return (React.createElement("div", { key: item.id, className: "dummyClassObject"},
                React.createElement("span", { className: "dummyClassLabel" }, item.label)));

Example function:

function linking(link) {
console.log("Redirecting to" + " " + link);
window.open(link);
}

When I append onClick: linking to the div element, it works fine (other than it missing a parameter). When I try to pass a parameter the traditional way (linking(item.link)), it calls the function repeatedly. I did google this – this is expected behavior. How else can I pass an argument without accidently calling the function?

If this is a stupid question – sorry 🙂

3

Answers


  1. From the description of your issue, i think you want to do

    onClick: () => linking( item.link )
    
    Login or Signup to reply.
  2. onClick: linking is perfectly valid, it’s just passing the function reference. It’s not missing any parameters when used like that. Adding the parentheses will call the function now, but you actually want it to be called in response to the user clicking the button; it needs a function reference to do so, because it needs to be able to call the function itself when the event happens. Using onClick: linking(item.link) will call and execute the function and try to assign its return value (undefined) to the "onClick" property (which won’t do anything).

    On the other hand, while onClick: linking is valid, your function is expecting a different value than what it’s going to receive: an element’s click event handler is called with a MouseEvent object.

    What you probably want is to pass another function that calls your handler with the expected values, maybe along the lines of

    onClick: () => linking(item.link)
    

    This creates a new function, which doesn’t take any arguments (or if one is given, like an event object, it would just be ignored), and instead calls your function with the given arguments when it is invoked.

    Login or Signup to reply.
  3. Try the following piece of code:

    onClick: () => linking(item?.link)
    

    or, for functional component:

    onClick={() => linking(item?.link)}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search