N N
N N

Reputation: 1638

How to pass arguments to function in functional component in React

How can I pass arguments to a function in functional component? As far as I know, creating function in jsx is not good practice right?

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(data);
  }
  return <button onClick={handleClick(??)} value='Foo'>Click</button>
}

Upvotes: 4

Views: 26745

Answers (3)

Prakash Kandel
Prakash Kandel

Reputation: 1043

This will work

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(data)

  }
  return <button onClick={(event) => handleChange(event, 'Some Custom Value')} value='Foo'>Click</button>
}

Or if you only want to send the data property, you could do something like

function MyComponent(props) {
  function handleChange(data){
    console.log(data)

  }
  return <button onClick={(event) => handleChange('Some Custom Value')} value='Foo'>Click</button>
}

Upvotes: 11

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

There isnt anything particularly wrong with using a non-arrow function in React/jsx. People just use arrow-functions more often so they don't have to bind the this keyword.

Something like this would work perfectly fine.

function MyComponent(props) {
  function handleChange(event, data){
    console.log(event.target.value);
    console.log(props.data)
  }
  return <button onClick={(event, props.data) => handleChange(event)} value='Foo'>Click</button>
}

Upvotes: 1

Engineer
Engineer

Reputation: 1261

You can keep function outside of functional component,

MyComponent = (props) => {
  return <button onClick={(event, props.data) => handleChange(event, props.data)} value='Foo'>Click</button>
}
function handleChange(event, data){
  console.log(event.target.value);
  console.log(data);
}

Upvotes: 4

Related Questions