Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTML. Can it be done using the data-value attribute?

Main.jsx File:

import React from "react";
import { useState } from "react";
import { Link } from "react-router-dom";

import styles from "../styles/Main.module.css";

const FIELDS = {
  NAME: "name",
  ROOM: "room",
};

const Main = () => {
  const { NAME, ROOM } = FIELDS;

  const [values, setValues] = useState({ [NAME]: "", [ROOM]: "" });

  const handleChange = ({ target: { value, name } }) => {
    setValues({ ...values, [name]: value });
  };

  const handleClick = (e) => {
    const isDisabled = Object.values(values).some((v) => !v);

    if (isDisabled) e.preventDefault();
  };

  return (
    <div className={styles.wrap}>
      <div className={styles.container}>
        <h1 className={styles.heading}>Join</h1>

        <form className={styles.form}>
          <div className={styles.group}>
            <input
              type="text"
              name="name"
              value={values[NAME]}
              placeholder="Username"
              className={styles.input}
              onChange={handleChange}
              autoComplete="off"
              required
            />
          </div>
          <div className={styles.group}>
            <input
              type="text"
              name="room"
              placeholder="Room"
              value={values[ROOM]}
              className={styles.input}
              onChange={handleChange}
              autoComplete="off"
              required
            />
          </div>

          <Link
            className={styles.group}
            onClick={handleClick}
            to={`/chat?name=${values[NAME]}&room=${values[ROOM]}`}
          >
            <button type="submit" className={styles.button}>
              Sign In
            </button>
          </Link>
        </form>
      </div>
    </div>
  );
};

export default Main;

Answer №1

For a more streamlined approach, it may be beneficial to step away from React's single-page application logic and focus on the fundamentals of working with native form controls in a multi-page website.

In its most basic configuration, you would have a single page (index.html) containing the form. The form element should include an action attribute that directs to another page (chat.html).

Upon clicking the submit button, the form will transition to chat.html, passing along the completed input values as query parameters.

Subsequently, JavaScript can be utilized to break down the current URL, including its query parameters.

index.html

<form action="chat.html">
    <input type="text" name="name" value="" />
    <input type="text" name="room" value="" />
    <button type="submit">Submit</button>
</form>

chat.html

<script>

    // Instantiate a new URL object using the current URL string
    const url = new URL(window.location);

    // Retrieve the query parameters
    const params = url.searchParams;

    // Access each parameter by its name
    console.log(params.get('name'));
    console.log(params.get('room'));
</script>

Additional resources

  • Guide to extracting query parameters in JavaScript

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

Image not aligning to center - email

Struggling to center align an image at the top of an email due to code that hides it when the browser is larger than 520px. Is there a way to exempt this specific image and keep it centered? .mobile { display: none !important; font-size 0 !importa ...

I am encountering difficulties importing the React-hexgrid library

Although I have verified that the library path is correct, I am still encountering an error. Here is the code snippet: "react-hexgrid": "2.0.1", "react": "18.2.0" "next": "13.4.3" Click here to v ...

Unable to fetch valid JSON from a different domain using JQuery and AJAX

I'm having trouble accessing a JSON api from a specific adult-themed website. I've been trying to make it work but so far no luck. You can find my code snippet in this jsfiddle: http://jsfiddle.net/SSqwd/ and here is the script: $.ajax({url: &ap ...

The functionality of displaying one div while hiding another upon click seems to be malfunctioning

Can anyone lend a hand? I'm having trouble with my code - the section isn't showing up after clicking the button. <script> $("#img1").on('click', function() { $("#div1").fadeIn(); $("#div2,#div3,#div4").fadeOut(); }); $(" ...

Issue Encountered in NodeJS While Processing Multiple GET Requests

I have been developing a web application that utilizes a database containing game data. When a user clicks on a game, a GET request is made to an API to retrieve additional information for the selected game. My goal is to ensure that users can access detai ...

Angular File Sorting Error in Gulp detected

After including .pipe(angularFilesort()) in my gulp script, the task runs wiredep but never proceeds to the default task. It just stops after executing wiredep. However, if I remove .pipe(angularFilesort()), the script works perfectly fine. Can someone h ...

Having trouble assigning a value to the datapicker through the onchange event and the name attribute in the code below

const stateValues = { code: '', product: '', checked: 'false', jobCardNo: '', openDate: '', completionDate: '', serial: '', technicalNo: '', ...

Encountering difficulties with implementing and utilizing bootstrap in Symfony 5.3 with Encore plugin

While I am currently dealing with an older version of Symfony, I decided to create a new 5.3 Symfony application from scratch. However, I am facing difficulties when trying to integrate bootstrap into it. After consulting some documentation, I proceeded to ...

Utilizing AngularJS ng-show to conditionally display content based on data retrieved from an

I am facing an issue with implementing the ngShow directive in my code, where I am trying to display data fetched from an API call. However, despite everything else working correctly, the ngShow directive does not seem to be functioning as expected. Here ...

Accessing Cognito using ReactJS and fetching data with specific parameters

I'm currently attempting to retrieve the email of the user who is logged in and use it within my fetch() call. I have successfully obtained the email using getfirstapi() and used it in my form, but I am encountering issues when trying to pass it into ...

Bindings with Angular.js

I have developed an application similar to Pastebin. My goal is to allow users to paste code snippets and display them with syntax highlighting and other visual enhancements, regardless of the programming language used. To achieve this, I utilize Google&ap ...

From where does the require.js file originate?

Currently, I am learning Angular 2 from the tutorial available at https://github.com/pkaul/maven-typescript-example. Once I proceed with the 3rd step (mvn jetty:run), a runnable war folder is generated in the example-webapp/target directory. However, I ha ...

Simultaneously modifying the status of multiple children

In an attempt to control the visibility of GalleryItem components, I am toggling skill components on and off that were utilized to create those projects. The goal is to: Show ALL if no skills have been toggled If one or more skills are toggled, display onl ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

Leverage the power of NextJS by enforcing dependencies with the outputStandalone option

Introducing the innovative outputStandalone experimental feature (https://nextjs.org/docs/advanced-features/output-file-tracing#automatically-copying-traced-files-experimental) allows for the creation of a separate folder after building that includes all n ...

Leveraging the power of React and Nodejs to seamlessly share code across both the front-end

Currently, my front-end is built in React and backend is developed using Nodejs with the Adonisjs framework. I am looking to share some code between the client and server components of the application. Unfortunately, due to company policies, my team is una ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

Attempting to implement a text border in React Native

I am currently working on creating a stylish "box" around text, which includes a border and background color for the text itself (in this case, just a single character). However, I am facing an issue where the upper bound of the view is cutting off part of ...

Why does "react-hot-loader/babel" cause issues in my build process?

After incorporating "react-hot-loader/babel" into my .babelrc file, I am encountering issues with my React components. In particular, the code snippet in question is as follows: export default class Editor extends React.Component { componentDidMount ...

Issues with `Float:left` not functioning as expected on a div with dynamically changing

I'm currently working on setting up a base div that I can easily duplicate whenever I need to add new content to my website. Here's how the initial HTML structure looks: <div class="post"> <p class="date">17/03/1014</p> <h1& ...