Submit Button Is Navigating Away From the Page

  Kiến thức lập trình

I’m currently building a website using Next.js (React) and Strapi, and I’ve encountered an issue while setting up the newsletter subscription form.

Here are the problems I’m facing:

  • useState Issue: The useState for hasSignedUp isn’t behaving as expected. When hasSignedUp is set to true, everything works fine: the <h4> displays correctly if email.length > 0, and the page refreshes when the submit button is clicked. However, when hasSignedUp is set to false by default (as it should be), the functionality breaks. I’m not sure why this is happening.

  • Page Refresh: The page is refreshing after form submission, even though I’ve used preventDefault() in the form’s onSubmit handler.

  • Unexpected Navigation: When I click submit, the browser navigates to a new URL: "http://localhost:3000/blog?email=fsfssfsdf", where "fsfssfsdf" is the input I typed before submitting. The console logs also show this navigation ("http://localhost:3000/blog?email=fsfssfsd"). There is no action associated with this input, so not sure what is happening.

This is my SubscribeToNewsletter component:

"use client";
import { useState } from "react"; // Creating a use state to track what the user is typing in the input section

const SubscribeToNewsletter = () => {
  console.log("🎉 SubscribeToNewsletter component rendered 🎉");

  const [email, setEmail] = useState("");
  const [hasSignedUp, setHasSignedUp] = useState(false);

  const onChange = (e) => {
    console.log("Email input changed:", e.target.value);
    setEmail(e.target.value);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    console.log("On submit has been clicked");
    console.log("Current email:", email);

    if (email.length) {
      console.log("Email is valid, updating hasSignedUp state");
      setHasSignedUp(true);
    } else {
      console.log("Email is empty or invalid");
    }
  };

  return (
    <section className="newsletter">
      {hasSignedUp ? (
        <h4 className="newsletter__thanks">
          Thank you for signing up to our newsletter !
        </h4>
      ) : (
        <>
          <div className="newsletter__info">
            <h4>Subscribe to our newsletter</h4>
            <p className="copy">
              Unlock Exclusive Insights and Stay In the Know – Subscribe to Our
              Newsletter Today to always stay in touch
            </p>
          </div>
          <form className="newsletter__form" onSubmit={onSubmit}>
            <input
              id="email"
              name="email"
              type="text"
              className="newsletter__email input"
              placeholder="Enter your E-mail address"
              value={email}
              onChange={onChange}
            />
            <button
              type="submit"
              className="newsletter__subscribe btn btn--medium btn--turquoise"
            >
              SUBSCRIBE
            </button>
          </form>
        </>
      )}
    </section>
  );
};

export default SubscribeToNewsletter;

This is my main blog page component, on which the SubscribeToNewsletter component should be rendered:

import HighlightArticle from "../_components/Blog/HighlightArticle";
import SubscribeToNewsletter from "../_components/Blog/SubscribeToNewsletter";

export default function Page() {
  console.log(" The BLOG page has been mounted");

  const highlightArticleData = {
    headline: "3 tips for a super fast takeoff",
    excerpt:
      "Improving your take-off phase in surfing is a fundamental step toward riding waves with more confidence and style. Improving your take-off phase is a gradual process, and it may take time to master. Be patient, stay committed to practice, and enjoy the journey of becoming a better surfer. With dedication and persistence, you'll see progress and have more enjoyable rides. Here is how:",
    slug: "takeoff",
    featuredImage: "/assets/hero-experience.png",
  };

  return (
    <main className="blog-page ">
      <HighlightArticle data={highlightArticleData} />
      <SubscribeToNewsletter />
    </main>
  );
}

What I’ve tried so far, to fix the issue:

  • I’ve been troubleshooting an issue with my useState setup, and here’s what I’ve observed:

  • I changed the useState default value from false to true to see if it would render in the browser:

const [hasSignedUp, setHasSignedUp] = useState(true);

With this setup, when I submit an email through the form, the <h4> element renders the thank you message as expected. However, if I click submit without entering any text (email.length < 0), the page reloads.

  • To narrow down the issue, I added several console.log statements. Only the first one (console.log("🎉 SubscribeToNewsletter component rendered 🎉")) is appearing in the VSCode terminal, but I’m not seeing any logs from the others in the browser’s console. Despite this, I am getting a 200 OK response from the network.

  • I even tried deleting my existing component and creating a new SubscribeToNewsletter component from scratch, but the issue persists.

  • I also tested with a minimal example, but it didn’t display the input value in the console log:

"use client";
import { useState } from "react";

const TestInput = () => {
  const [text, setText] = useState("");

  const handleChange = (e) => {
    setText(e.target.value);
    console.log("Input value:", e.target.value);
  };

  return (
    <input
      type="text"
      value={text}
      onChange={handleChange}
      placeholder="Type something..."
    />
  );
};

export default TestInput; 

11

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT