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

   );
}

Navneet kumar
  • 1,696
  • 1
  • 17
  • 26

2 Answers2

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
CevaComic
  • 2,056
  • 2
  • 6
  • 12
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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    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.) – T.J. Crowder Jun 13 '20 at 13:42