Looking to incorporate a raw JavaScript file into a React project

I have successfully converted my HTML and CSS components to React, but I am facing some challenges with the JS part. I attempted to use react-helmet, but encountered an error:

Cannot read property 'addEventListener' of null

Here is my React.js file:

import React,{ Component }from 'react'
import { Helmet } from 'react-helmet'
import './ContactForm.css'

export default class ContactForm extends Component {
    

    render() {
        return (
            <>
                <section>
                    <div className="container">
                        <form action="https://formsubmit.co/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e18c98a18c98848c80888dcf828e8c">[email protected]</a>" method="POST" id="my-form"&...
    </div>
</div>
</pre>
<p>Original HTML/CSS/JS code:</p>
<p><div>
<div>
<pre class="lang-js"><code>window.addEventListener("DOMContentLoaded", function () {
  // get the form elements defined in your form HTML above

  var form = document.getElementById("my-form");
  // var button = document.getElementById("my-form-button");
  var status = document.getElementById("status");

  // Success and Error functions for after the form is submitted

  function success() {
    form.reset();
    status.classList.add("success");
    status.innerHTML = "Thanks!";
  }

  function error() {
    status.classList.add("error");
    status.innerHTML = "Oops! There was a problem.";
  }

  // handle the form submission event

  form.addEventListener("submit", function (ev) {
    ev.preventDefault();
    var data = new FormData(form);
    ajax(form.method, form.action, ...
etc.

Answer №1

React allows you to seamlessly integrate JavaScript code within its framework.

<script src="./main.js"></script>   //--> is how HTML imports a JS file

To ensure your JavaScript code works effectively with React, proper formatting is essential.

Here's an example using functional components and hooks:

import React, { useState } from "react";
import "./ContactForm.css";

export default function ContactForm() {
   const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    massage: ""
  });

  const updateFormData = (e) =>
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });

  const submitForm = (e) => {
    e.preventDefault();
    console.log(formData);
    fetch("https://formspree.io/mbjzbwaj", {
      method: "POST",
      body: JSON.stringify({ formData }),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const { firstName, lastName, email, massage } = formData;

  return (
    <section>
      <div className="container">
        <form id="my-form" onSubmit={submitForm}>
          <div className="form-group">
            <label htmlFor="firstName"> First Name</label>
            <input
              type="text"
              id="firstName"
              name="firstName"
              value={firstName}
              onChange={(e) => updateFormData(e)}
            />
          </div>

          <div className="form-group">
            <label htmlFor="lastName">Last Name</label>
            <input
              type="text"
              id="lastName"
              name="lastName"
              value={lastName}
              onChange={(e) => updateFormData(e)}
            />
          </div>

          <div className="form-group">
            <label htmlFor="email">Email</label>
            <input
              type="email"
              id="email"
              name="email"
              value={email}
              onChange={(e) => updateFormData(e)}
            />
          </div>

          <div className="form-group">
            <label htmlFor="massage">Massage</label>
            <textarea
              name="massage"
              id="massage"
              cols="30"
              rows="10"
              value={massage}
              onChange={(e) => updateFormData(e)}
            ></textarea>
          </div>
          <button type="submit">Submit</button>
        </form>
      </div>
     </section>
  );
}

Demo : stackblitz


EDIT

To integrate Formspree with React, utilize a specific hook for simplicity. Detailed documentation can be found here.

Start by importing formspree:

npm i @formspree/react

ContactForm.js

import React from 'react';
import { useForm } from '@formspree/react';

export default function ContactForm() {
  const [state, handleSubmit] = useForm('######'); // hash id
  if (state.succeeded) {
    return <div>Sucess!</div>;
  }
  return (
    <form onSubmit={handleSubmit}>
      <div className="form-group">
        <label htmlFor="firstName"> First Name</label>
        <input type="text" id="firstName" name="firstName" />
      </div>

      <div className="form-group">
        <label htmlFor="lastName">Last Name</label>
        <input type="text" id="lastName" name="lastName" />
      </div>

      <div className="form-group">
        <label htmlFor="email">Email</label>
        <input type="email" id="email" name="email" />
      </div>

      <div className="form-group">
        <label htmlFor="massage">Massage</label>
        <textarea name="massage" id="massage" cols="30" rows="10"></textarea>
      </div>
      <button type="submit" disabled={state.submitting}>
        Submit
      </button>
    </form>
  );
}
  • The hash id required can be found in the "form details" under the "integration" tab. In your case, it was "...formspree.io/mbjzbwaj" (hash id)

Answer №2

When working with React, event handling and other functionalities are approached in a slightly different manner.

To link an event with a handler, you can use the following syntax:

<button onClick={handleClick}>CLICK</button>

In this example, onClick represents the event, while handleClick is the designated handler function.

Prior to your render function, you can define a handler like this:

const handleClick = () => {
  console.log("Clicked!");
  // perform necessary functionality... 
}

You also have the option to access the event by passing (e)

const handleClick = (e) => {
  e.preventDefault(); // prevent the default action
  console.log("Clicked!");
  // perform necessary functionality... 
}

If you're transitioning your code to React, it's recommended to test it out using this approach and referring to the official documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating JQuery UI Resizable functionality into a Meteor project after creating an object

After adding an object to a list of JQuery Resizable objects in my Meteor app, I noticed that the object doesn't become resizable until I refresh the page. I'm wondering what kind of event listener or solution should be implemented and where it ...

Removing non-integer values from elements within an array using JavaScript

As a newcomer to programming, I have encountered similar questions before and attempted to apply the solutions without success. Consider the following array: var myArray = [24.203, 12*45, 000-1, 4567+00]; I aim to remove all non-integers from this array ...

Array Not Defined

I am attempting to create a for loop using a variable, but it seems like I'm running into an issue. No matter what I try, the length of tempArray always remains undefined. I can't figure out why this is happening. Can anyone offer some assistance ...

Tips for adjusting the "active" navigation class across various pages using base.html

I have my main navigation bar located in the base.html file and I include it in all other pages. However, I currently have the class "active" assigned to the home page link, causing it to remain active on all other pages as well. <ul class="navbar-nav" ...

Getting all inline styles from an HTML string using JavaScript

(JavaScript) I am working with an html email template stored as a string. Is there a way to extract all the inline styles used in the template? For instance, if I have this input: <div style="min-width:300px;max-width:600px;overflow-wrap:break-word ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...

What is the most stylish method for merging a removeCartItem function with an addCartItem function?

Is there a way to combine these functions into a more concise and elegant piece of code? While the current setup works fine, it feels redundant to have two large functions that essentially do the same thing. const modifyCartItem = (cartItems, productToMo ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

The form action seems to be unresponsive when utilized within a vue-bootstrap form

I'm utilizing a form submission service called formsubmit.co, which allows forms to receive input data via email without the need to develop a backend for storing and transmitting data. Formsubmit handles all the storage and sending processes. Accordi ...

"Troubleshooting: Issue with AngularJS ng-repeat not functioning properly when using an

I am working with a simple list <ul> <li ng-repeat="spiel in spielListe">Do something</li> </ul> Along with a perfectly connected controller $scope.spielListe = []; There is also a method that adds objects to the array in th ...

Error message: "localStorage not defined - Pairing Recoil with Next.js"

I've implemented a localstorage effect following the guidance in the Recoil documentation. However, upon running my application, I encounter a localStorage is not defined error in the browser. Initially, I assumed that this might be executing on the s ...

Using CSS alone, incorporate two images within a section in HTML5

Is there a way to add two images inside a section using CSS to make them look like this: https://i.sstatic.net/74JSK.png However, the only result I can achieve with CSS looks like this: https://i.sstatic.net/TWrSR.png I could use divs in HTML and add th ...

Scroll the div until it reaches the top of the page, then make it fixed in place

Let's dive right in: The code I am working with is as follows: <div id="keep_up"> <div id="thread_menu"> <div id="new_thread"> </div> </div> </div> And here is my CSS: #keep_up { po ...

A basic webpage created using ASP.NET featuring simple HTML text

Is it acceptable to manually code HTML, such as <p>, <ul>/<li>, <h3>, <h4>, <blockquote> tags, into a Content Page that already has an existing Master Page? The content is similar to a blog post. Are there better desig ...

Double MySQL Inserts happening with a single submission

My PHP file manages user signups using MySQL, but there's a recurring issue where users' input gets duplicated. https://i.sstatic.net/A8n6X.png The form below shows part of the code that handles the signup process... if ($_SERVER["REQUEST_MET ...

Ensure that the dropdown <select> remains open even while filtering through options

I am currently working on implementing a mobile-friendly "filtered dropdown" design: https://i.sstatic.net/SYjQO.png Usually, a <select> control remains closed until the user clicks to open it. Is there a straightforward way to keep it always open ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Creating a simple vertical layout with a fixed header and footer using basic HTML and CSS, allowing for easy stretching and customization

Looking for advice on creating a vertical layout with a static height header and footer, while allowing the center to occupy all available space and adjust to the window height. header ------ center ------ footer Any suggestions would be greatly appr ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

Leveraging the useEffect hook to make multiple API calls in ReactJS

I have a useEffect function in my react component where I am calling the API videoGridState. The issue I am facing is that the API is being called twice; once when the page initially reloads and again when the count changes. I want it to be called only onc ...