Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing 2 functions in onChange in react

I have a parent component and a child component. I want to pass a function from parent component to child in onChange and also another function in the child component to update a state in the child component. How can this be done?

Parent

export function Fruits() {
  const onChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    alert(e.target.value);
  };

  return (
    <div>
      <RadioBtnGroup
        options={FruitsOptions}
        name={"Fruits"}
        label="Choose Fruit:"
        radioBtnChangeHandler={onChangeHandler}
      />
    </div>
  );
}

Child

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export function RadioBtnGroup({
  ...
}: React.HTMLAttributes<HTMLInputElement> {
  
  const [ariaValue, setAriaValue] = useState("");

  return (
    <>
      {label && (
        <h3 id="fruits-radio-group">{label}</h3>
      )}
      <div
        role="radiogroup"
        aria-labelledby="fruits-radio-group"
        aria-activedescendant={ariaValue}
        tabIndex={0}
      >
        {options?.map((option, index) => (
          <RadioBtn
            key={`radioOpt-${option.value}`}
            onChange={() => {
              radioBtnChangeHandler; 
              setAriaValue(e.currentTarget.value);
            }} //////////
            id={`radioOpt-${option.value}`}
            label={option.label}
            value={option.value}
          />
        ))}
      </div>
    </>
  );
}

>Solution :

You’ll have to call the radioBtnChangeHandler with the event from the onchange event.

This is a link to a working implementation of the example you provided https://codesandbox.io/s/intelligent-haze-jfii5x?file=/src/RadioBtnGroup.tsx

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading