-2

I have a react component where i want to call same arrow function with different arguments, but i am stuck on how to pass argument to it, now i am questioning myself can i do it ?


function Register(props) {

  const handleChange = (event) => {
    // here i want receive multiple arguments here eg. fromText1, fromText2
  }

  return (
        <React.Fragment>
           <TextField
           ...
           onChange={handleChange} // handleChnage('fromText1');
          />

          <TextField
           ...
           onChange={handleChange} // handleChnage('fromText2');
          />
         ....
        </React.Fragment>

   );
}

1
  • 1
    Thank you @devserkan, I should have known there was a good dupetarget. Commented Jun 13, 2020 at 13:42

2 Answers 2

2

Just do a double arrow function like this:

const [state, setState] = React.useState({})
const handleChange = name => e => {
    setState({
        ...state,
        [name]: e.target.value
    })
}

// later in your code

<TextField
    ...
    onChange={handleChnage('fromText1')}
/>

// this will cause the change of value of formText1 in your state
Sign up to request clarification or add additional context in comments.

Comments

0

You have a couple of options, but the typical solution in a React functional component is to use an arrow function wrapper:

onChange={e => handleChange(e, "fromText1")}

With that, the first argument would be the event object and the second would be the string "fromText".

Alternatively, you could use bind:

onChange={handleChange.bind(null, "fromText1")}

With that, the first argument would be the string "fromText" and the second would be the event object.

The event object also has a couple of handy properties, such as target (the DOM element the event was targeted at) and currentTarget (the DOM element where the event handler was attached — React synthesizes this a bit as it uses delegation internally).

1 Comment

Of course this has been covered before. Having been silly enough to write the answer above, I'll leave it rather than deleting it, but I've marked it CW so people don't mistake my doing that as being related to rep. (CW answers don't create rep.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.