skip to Main Content

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

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

2

Answers


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

    onChange={(e) => {
                  radioBtnChangeHandler(e); 
                  setAriaValue(e.currentTarget.value);
                }}
    

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

    Login or Signup to reply.
  2. 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={(e) => {
                  radioBtnChangeHandler(e); 
                  setAriaValue(e.currentTarget.value);
                }} //////////
                id={`radioOpt-${option.value}`}
                label={option.label}
                value={option.value}
              />
            ))}
          </div>
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search