I want to use jquery in react. I have an input field in my project.I'm making a match event with 'this.state.value' in my input field. In this control, my input borders have green borders if they match, and red borders if they don't. I want the border to stay with permanent color if there is no match. How can i do it ?
<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} />
This is css :
input[type=text].redBorder:focus{
border: 3px solid red;
}
You can use a state variable to check if the input is valid, and change the classname accordingly. Here is a working 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>
);
}
This is my solution. You may try it 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;
}