Home > other >  How do I make a button act like a submit button for a form when it's in a different component i
How do I make a button act like a submit button for a form when it's in a different component i

Time:09-17

I am trying to make a simple "My Account" page in react,where a user can edit his/her account details. I have two components, the navbar and the form itself, however, the submit button for the form is in the navbar component whereas the form itself is in the accountdetails component. They both share a parent component (App.js). How do I make the button in the top right hand corner of the screen (edit button) act as a submit button for the form so that all my form validation works and a user can't submit incorrect data.

You can find the corresponding code here: My Accounts page with a form to edit account details

CodePudding user response:

You can try creating an invisible submit button in the form component and pass a ref to it from your App.js component. You can then create a function in App.js which programmatically clicks the invisible button in the form. This function can then be passed to the button on the navbar and triggered onClick. See example bellow:

App.js

...
export default App = () => {
    const submitButtonRef = useRef(null);
    
    const submitForm = () => {
        if (submitButtonRef) {
            submitButtonRef.current.click();
        }
    }
    
    return (
        ...
            <Navbar submitForm={submitForm} />
            <FormComponent submitButtonRef={submitButtonRef} />
        ...
    )
}

Navbar component

...
export default Navbar = ({submitForm}) => {

    return (
        ...
            <button onClick={()=>submitForm()}>Submit</button
        ...
    )

Form component

...
export default FormComponent = ({submitButtonRef}) => {

    return (
        ...
            <button 
                style={{display: "none"}} 
                htmlType="submit" 
                ref={submitButtonRef}
            >
                Submit
            </button>
        ...
    )

I'm just a newbie so any sugestions would be very much appreciated. Thank you!

  • Related