My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Submit form component from outside in React by using Event constructor!

Submit form component from outside in React by using Event constructor!

YOUSSEF EL BEQQAL's photo
YOUSSEF EL BEQQAL
·Aug 26, 2021·

3 min read

Before you read this article I assume you are familiar with Forms and Hooks in React. If not just follow me.

Step 1:

Create a new project we're using create-react-app

npx create-react-app submit-form-outside-component

Step 2:

After we create a new project using create-react-app. Now we have to clean up the project a little bite.

remove app.css, index.css, reportWebVitals.js, and logo.svg.

Open app.js file and update with this code below:

const App = () => {
  return (
    <div>
      <h1>Hello React App</h1>
    </div>
  );
}

export default App;

Open index.js file and update with this code below:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

After that modifications run:

npm start

Open your favorite browser you should see:

screencapture-localhost-3001-2021-08-24-18_32_32.png

Greate, you run react app successfully!

Step 3:

Now, We have to create our form components and call it inside App component.

Create folder name components in your directory. and then create file name Form.js and copy past code bellow

const Form = ()  => {
    return (
        <div>
            <h2>form</h2>
        </div>
    )
}

export default Form;

Now we have to import our Form component in App Component

import Form from "./components/Form";

const App = () => {
  return (
    <Form />
  );
}

export default App;

Now our UI should display form text

screencapture-localhost-3001-2021-08-24-18_54_51.png

Update Form.js with code bellow:

import { useState } from "react";
const Form = ()  => {
    const [dogName, setDogName] = useState("");
    const handleChange = (e) => {
        setDogName(e.target.value)
    }
    const submit = (e) => {
        e.preventDefault();
        console.log("submit: ", dogName)
    };
    return (
        <div>
            <h2>form</h2>
            <form>
                <input type="text" placeholder="Enter your dog name..." value={dogName} onChange={handleChange} />
                <button onClick={submit}>SUBMIT</button>
            </form>
        </div>
    )
}

export default Form;

Let me explain the code more:

  • useState() hook for handle our dogName state.
  • handleChange for controlle our input and update dogName state in onChange event.
  • submit function for submit form, later we gonna submit form outside Form component.

In the Last Step, We gonna submit our form from App.js parent component.

Update Form with code bellow:

import { useState } from "react";
const Form = ({formRef})  => {
    const [dogName, setDogName] = useState("");
    const handleChange = (e) => {
        setDogName(e.target.value)
    }
    const submit = (e) => {
        e.preventDefault();
        console.log("submit: ", dogName)
    };
    return (
        <div>
            <h2>form</h2>
            <form ref={formRef} onSubmit={submit}>
                <input type="text" placeholder="Enter your dog name..." value={dogName} onChange={handleChange} />
            </form>
        </div>
    )
}

export default Form;
  • ref for reference our form from parent component and fire event from this ref.
  • onSubmit event for submitting the form when event call.

The last change in this article we gonna update parent component, The App component with code bellow:

import { useRef } from "react";
import Form from "./components/Form";

const App = () => {
  const formRef = useRef();
  const fireSubmitEvent = () => {
    formRef.current.dispatchEvent( new Event("submit", { cancelable: true , bubbles: true} ) );
};
  return (
    <>
      <Form formRef={formRef} />
      <button onClick={fireSubmitEvent}>
        Submit Form Outside
      </button>
    </>
  );
}

export default App;

Now, you can submit a form outside of Form component, Greate!

Note: This is my first post, I hope you learn something from it.

Thanks!