Home > Blockchain >  Onclick calling functions diffrences
Onclick calling functions diffrences

Time:02-24

can I am on working on a react project and I was wondering what is a difference between different onClick function calling ,meaning:

<Button onClick={function}> 
<Button onClick={function()}>

<Button onClick={()=>function()}>
<Button onClick={()=>function}>

I have seen multiple methods but I still can't get a grap on the core of their differences,thanks!

CodePudding user response:

It's 5 Differences Between Arrow and Regular Functions

https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/

CodePudding user response:

In the original post, there's already a post on function() vs function.

In summary (and in layman terms), though, there are 2 ways on how you handle onClick.

When you want to pass some value to the function

//the button
<button onClick={() => myFunction('I am a click')}>Button</button>


//the function
const myFunction = (value) => {
     console.log(value) //prints 'I am a click'
}

When you do NOT need to pass any value (events/default props will be passed by default)

//the button
<button onClick={myEvent}>Button</button>


//the function
const myFunction = (event) => {
     console.log(event) //prints the button element
}

Creating a custom Button component with custom props.

const MyButton = ({ onClick }) => {
   const customOnClick = () => {
       onClick('Somebody', 'Special'); //we call the onclick here
   }   

   return <button onClick={customOnClick}>Click Me</button>
}

const App =() => {

   //the onClick in MyButton component actually triggers this function.
   const onClick = (value, value2) => {
       console.log(value,value2) //prints "Somebody Special"
   }
   return (<MyButton onClick={onClick} />) // i do not need to specify the props to pass
}

CodePudding user response:

<Button onClick={function}>

Assigns the reference of a declared function to the click listener. This is preferable.

<Button onClick={function()}>

Assigns the result of calling the function to the click listener. You probably don't want to do this unless the function returns a function of its own, also known as a closure.

<Button onClick={() => function()}>

This is basically the same as the first example but in React this function expression is defined each time the component is rendered so you may have some performance issues if your app scales. The first example is preferable.

<Button onClick={() => function}>

Doesn't do anything useful. Avoid.

  • Related