I am interested in incorporating jQuery into my React development project

I'm trying to implement jQuery in React. I have an input field in my project that I am using to create a match event with 'this.state.value'. When the content of the input field matches, I want the borders to turn green and red if they do not match. However, I would like the border color to remain permanent even if there is no match. How can I achieve this?

<input className={this.state.value1 != this.state.value1.match(/^[a-zA-ZĞÜŞİÖÇğüşiöç]+$/) ? "redBorder inputInfo" : "greenBorder inputInfo"} name="value1"  type="text"  placeholder="Name" value1={this.state.value1} onChange={this.handleChange} />

Here is the CSS for it:

input[type=text].redBorder:focus{
    border: 3px solid red;
}

Answer №1

Utilizing a state variable to validate input and dynamically change the classname is an effective approach. For a working example, refer to this codesandbox

styles:

.App {
  font-family: sans-serif;
  text-align: center;
}

input[type="text"] {
  border: 1px solid black;
}

input[type="text"].redBorder {
  border: 1px solid red;
}

input[type="text"].greenBorder {
  border: 1px solid green;
}

input[type="text"]:focus {
  outline: none;
}

Handling Input:

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [inputIsValid, setInputIsValid] = useState(null);
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    if (inputValue.length > 0) {
      if (inputValue.match(/^[a-zA-ZĞÜŞİÖÇğüşiöç]+$/)) setInputIsValid(true);
      else setInputIsValid(false);
    } else setInputIsValid(null);
  }, [inputValue]);

  const handleValueChange = (e) => setInputValue(e.target.value);

  return (
    <div className="App">
      <input
        type="text"
        className={
          inputIsValid === null
            ? ""
            : inputIsValid
            ? "greenBorder"
            : "redBorder"
        }
        value={inputValue}
        onChange={handleValueChange}
      />
    </div>
  );
}

Answer №2

Here is the solution I came up with. Feel free to test it out on my codesandbox.

import "./styles.css";
import React, { useState } from "react";
export default function App() {
  let [borderClass, setBorderClass] = useState("");
  let pattern = /^[a-zA-ZĞÜŞİÖÇğüşiöç]+$/;
  let handleChange = (e) => {
    if (e.target.value === "") {
      setBorderClass("");
    } else {
      if (e.target.value.match(pattern)) {
        setBorderClass("greenborder");
      } else {
        setBorderClass("redborder");
      }
    }
  };
  return (
    <div className="App">
      <input type="text" className={borderClass} onKeyUp={handleChange} />
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
}
input[type="text"]:focus {
  outline: none;
}
.greenborder {
  border: 1px solid green;
}
.redborder {
  border: 1px solid red;
}

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

CSS designs that adapt with the screen: Triangles in

I'm currently working on creating a responsive triangle using CSS. I want both the height and width of the triangle to adjust as the window size changes. Below is my static code: #triangle { z-index: 2; width: 0; height: 0; position:absolute ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

"Utilizing the datepicker functionality in Rails with jQuery UI

I am looking to integrate the datepicker widget into one of my select fields within a Rails 3.2.13 application with Ruby 1.9.3.p325 installed. To achieve this, I have incorporated the 'jquery_datepicker' gem along with 'jquery-rails' an ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Using process.env.PORT in Reactjs to retrieve data in a production environment: a guide

I have encountered an issue with my code that fetches data from a database. It works fine on local host: async function getLikedAnimations(username) { const res = await fetch(`http://localhost:8080/animation-list/?username=${username}`); const js ...

If there are no spaces, text will be removed from my list group

While working on developing a forum, I encountered an issue where if I repeatedly input letters or words without any spaces, it causes everything to overlap. Below is an example highlighting this problem: https://i.sstatic.net/KStNq.png Although there is ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Using AngularJS to implement modules in a single controller

Currently, I am in the process of learning Angularjs and have two separate template pages - one for login (login.html) and another for the main content (index.html). To incorporate a chart into my index.html page, I am utilizing a directive from here. Th ...

`How can I load data into a table using a JSON object returned by Spring MVC and Hibernate-based RESTful web services?`

Looking to populate my JQuery table with JSON objects returned by Spring MVC. Here is the structure of my JSON data: { availDate: 1421508979000 custName: "Navin" custMobile: "8765432468" custEmail: "<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Retrieve the initial key from an object in javascript

Though seemingly simple, I'm stuck on finding the solution: Within my jquery object (displayed in console.log): { id_ship: "1", id_company: "1", code: "DE", // other properties... } My goal is to extract the first key from th ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

Is it possible for PHP to not provide an image to HTML?

I'm currently facing an issue trying to display an image in HTML using a PHP script. Despite my best efforts, it's not functioning as expected :-( Here is the code snippet from my image.php script: <? $_GET['f'] = 'all_thre ...

The icons at the bottom of the page are not properly aligned

I am having trouble aligning my footer icons, specifically the first 2 images. While the bootstrap icons are centered correctly, the first 2 images are not aligning as expected. I have tried various methods like align-items-center, justify-content-center, ...

Guide on including a sum (integer) property in the JSON output of my API

Currently, I am working on an API using Express.js. In one of my functions named getAll, my goal is to not only return an array of records but also include the total number of records in the response. The code snippet below showcases how I have been handli ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Are you experiencing issues with your Ajax request?

I've been struggling to retrieve json data from an API. Despite my efforts, the GET request seems to be executing successfully and returning the correct data when I check the Net tab in Firebug. Can anyone offer advice on what could be going wrong or ...

Using modules in Next.js to expand functionality

I am currently working on a project that I need to integrate into Next JS as a module. Utilizing npm link, I have successfully added the module to my Next JS repository as a component. However, the integration is breaking due to webpack loaders. Do I need ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...