Prompt Title: ReactJS Interview Questions

Created 1 year ago
Votes 0
Views 309 times
IT
0

Prompt Detail:

Sure! Here's an updated version of the Input component that includes inline validation to ensure that the input value only contains English letters:

javascript
import React, { useState } from "react"; const Input = () => { const [inputValue, setInputValue] = useState(""); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); const handleChange = (event) => { const value = event.target.value; const validLetters = /^[A-Za-z]+$/; if (validLetters.test(value)) { setInputValue(value); setError(null); } else { setError("Name must contain only English letters"); } }; const handleBlur = async () => { setIsLoading(true); try { // Perform async validation here, for example: const response = await fetch(`https://api.example.com/validate?input=${inputValue}`); const data = await response.json(); if (!data.valid) { setError("Invalid input"); } } catch (error) { console.error(error); setError("Error validating input"); } finally { setIsLoading(false); } }; return ( <div> <label htmlFor="input">Input:</label> <input id="input" type="text" value={inputValue} onChange={handleChange} onBlur={handleBlur} /> {isLoading && <p>Validating input...</p>} {error && <p>{error}</p>} </div> ); }; export default Input;

In this updated version, the handleChange function includes a regular expression pattern that matches only English letters, and checks the input value against that pattern before updating the input state and clearing any error message. If the input value does not match the pattern, an error message is displayed inline below the input field. The async validation is performed in the handleBlur function as before.

avatar
Bowen
Shared 1 prompt
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
2
react error
1 year ago 2023-04-07 11:13:29 tayyeb chaudhary
0
0
Implementación PWA con React.
1 year ago 2023-04-29 16:26:27 Alex