In React, the method to display an error message for a particular input is to use conditional rendering. You can create a state variable that represents the error message and update it based on the validation of the input. Then, in the JSX code for the input, you can use a conditional statement to render the error message if the state variable is not empty. For example:
import React, { useState } from 'react';
function InputWithError() {
const [inputValue, setInputValue] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const handleInputChange = (event) => {
const value = event.target.value;
// validation logic here
if (value.length < 5) {
setErrorMessage('Input must be at least 5 characters');
} else {
setErrorMessage('');
}
setInputValue(value);
}
return (
<div>
<input type="text" value={inputValue} onChange={handleInputChange} />
{errorMessage && <p>{errorMessage}</p>}
</div>
);
}
In this example, we have an input element with a value of inputValue
and an onChange
event handler which calls handleInputChange
function. The handleInputChange
function updates the inputValue
state and sets the errorMessage
state based on the validation logic. The error message is only displayed if the errorMessage
state is not empty using a conditional statement in the JSX code.
Asked: 2022-07-18 11:00:00 +0000
Seen: 1 times
Last updated: Feb 26 '22