Home > Software design >  pass onClick function as a props to sub component
pass onClick function as a props to sub component

Time:01-03

I have handelSubmit function that is post data in backend. Now I want to pass this function as a prop to child component But I get warning. How can I approach this?

this is my function that I need to pass in parent component

const handleSubmit = (e) => {
    e.preventDefault();
    request(JSON.stringify(staff));
  };



 <SubmitButton
   loading={loading}
   formValid={errMessage.formValid}
   handleSubmit={handleSubmit}
  />

sub component

function SubmitButton(formValid, isActive, handleSubmit, loading) {
return(
 <button
   className={formValid ? `submit ${false ? "active" : " "}` : "disable"}
   type="button"
   onClick={() => handleSubmit()}      ***//how can I solve here?***
   disabled={!formValid}
    > <span>Submit</span>
</button>
)
    }

CodePudding user response:

You're not using props correctly, you forgot {} :

function SubmitButton({formValid, isActive, handleSubmit, loading})

CodePudding user response:

try passing the event parameter in the OnClick eventHandler

onClick = {(e) => handleSubmit(e)}

CodePudding user response:

The problem is the component only receives a single param called props. If you try to de-structure it, you should use brackets {} to wrap your prop values in SubmitButton like below

function SubmitButton({formValid, isActive, handleSubmit, loading}) {
   return ...
}

Or

function SubmitButton(props) {
   const { formValid, isActive, handleSubmit, loading } = props  

   return ...
}

CodePudding user response:

You are defining the props as arguments to SubmitButton. But remember that props is a single argument that is passed to react components. You wanna destructure from props like this:

function SubmitButton({ formValid, isActive, handleSubmit, loading }) {
    return (
        <button
            className={formValid ? `submit ${false ? 'active' : ' '}` : 'disable'}
            type="button"
            onClick={() => handleSubmit()}
            disabled={!formValid}
        >
            <span>Submit</span>
        </button>
    );
}

CodePudding user response:

Include it inside value for the onClick prop like this:

<SubmitButton
  loading={loading}
  formValid={errMessage.formValid}
  handleSubmit={handleSubmit}
/>

<button
  className={formValid ? `submit ${false ? "active" : " "}` : "disable"}
  type="button"
  onClick={handleSubmit}
  disabled={!formValid}
>
  <span>Submit</span>
</button>
  • Related