Search code examples
reactjsreact-props

How to pass onChange and props in a function


I am trying to change the id of my input using props but I am also using an onChange event.

import React from "react";

function Toggle({ onChange }) {
  return (
    <>
    <input type="checkbox" id="switch" onChange={onChange} />
      <label htmlFor="switch"></label>
    </>
  );
}

export default Toggle;

I have tried like this:

import React from "react";

function Toggle({ onChange }, props) {
  return (
    <>
    <input type="checkbox" id={props.id} onChange={onChange} />
      <label htmlFor={props.id}>
      </label>
    </>
  );
}

export default Toggle;

How do I do this?


Solution

  • You are destructuring props, you can obtain the other values like this:

    { onChange, ...props }
    

    Your attempt

    ({ onChange }, props)
    

    Is destructuring the first argument, and assuming that there is a second one called props

    The ...props pattern from above is called a "rest" pattern, it also works with arrays