Reputation: 1829
I have a Textfield that would show an error if the password entered does not match with the confirm password. It does work, however, how do I shorten this out since I have to repeat these lines of codes to other textfield too.
<TextField
label="Password"
error={
errors.length > 0 && (
<ul>
{errors.map((err, index) => {
return <li key={index}>{err}</li>;
})}
</ul>
)
}
helperText={errors}
/>
<TextField
type="password"
id="standard2"
value={confirmPassword}
error={
errors.length > 0 && (
<ul>
{errors.map((err, index) => {
return <li key={index}>{err}</li>;
})}
</ul>
)
}
helperText={errors}
/>
How do I shorten that errors.map lines
of coddes.
Upvotes: 0
Views: 106
Reputation: 129
In material-UI, error props of the TextField component will accept the only boolean values. And helperText props will accept node. See here - https://material-ui.com/api/text-field/#textfield-api
You can simply create a component that will render errors messages with each field. For example
import { TextField } from '@material-ui/core';
const ErrorMsgs = ({ errors }) => (
<ul>
{errors.map((err) => (
<li key={err}>{err}</li>
))}
</ul>
);
function Form() {
return (
<form>
<TextField
label="Password"
error={errors.length > 0}
helperText={<ErrorMsgs errors={errors} />}
/>
<TextField
label="Password"
error={errors.length > 0}
helperText={<ErrorMsgs errors={errors} />}
/>
</form>
);
}
Upvotes: 1
Reputation: 12787
Use helperText
instead of error
to show message error.
<TextField
type="password"
id="standard2"
value={confirmPassword}
error={errors.length > 0}
helperText={
<ul>
{errors.map((err, index) => {
return <li key={index}>{err}</li>;
})}
</ul>
}
/>;
Upvotes: 1