4

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>
}
1
  • Is there anything in particular you'd like to make clear about functional-components? Commented May 14, 2019 at 3:28

3 Answers 3

11

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>
}

Sign up to request clarification or add additional context in comments.

Comments

4

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);
}

Comments

1

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>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.