'ReactJS Formik display error message in Red color
In ReactJS i am developing one Class component and using Formik for validation. I am able to do validation but error message is display as a normal color (black). How to add this error message inside any HTML element (span, div,etc..).
Below is the code to validation
import React, { Component } from 'react'
import { useFormik } from 'formik';
import { Formik, FormikProps, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
export class SubmitCase extends Component {
handleSubmit = (values, {
props = this.props,
setSubmitting
}) => {
setSubmitting(false);
return;
}
render() {
const formFields = {...this.state};
return (
<Formik
initialValues={{
subject: formFields.subject
}}
validate={(values) => {
let errors = {};
if(!values.subject)
errors.subject = "subject Required";
//check if my values have errors
return errors;
}
}
onSubmit={this.handleSubmit}
render={formProps => {
return(
<Form>
<Field type="text" placeholder="First Name" name="subject" value={formFields.subject} onChange={this.changeEventReact}/>
<ErrorMessage name="subject" />
<button type="submit">
Submit Form
</button>
</Form>
);
}}
/>);
}
}
I am using to display the message. Error message is displaying as a normal text(black color text). how to change it to red color.
Solution 1:[1]
Form formik docs <ErrorMessage>
component accepts a children prop as a function children?: ((message: string) => React.ReactNode)
so you can achieve what you want by return a component that wraps error message like this
<ErrorMessage name="subject">
{ msg => <div style={{ color: 'red' }}>{msg}</div> }
</ErrorMessage>
Solution 2:[2]
Also you can make css file for example - ErrorMessage.css with body:
.validation-error-message {
color: red;
}
And make js file for example - validators.js with body:
import './ErrorMessage.css';
export const ErrorMessageWrapper = (msg) => {
return (
<div className='validation-error-message'>
{msg}
</div>
)
}
And import, and use:
<ErrorMessage name="newPostText">
{ErrorMessageWrapper}
</ErrorMessage>
Solution 3:[3]
You can use component
props with your custom classes in ErrorMessage.
e.g.
<ErrorMessage component="div" name="name" className="help-block errors" />
<ErrorMessage component="div" name="email" />
// --> {touched.email && error.email ? <div>{error.email}</div> : null}
<ErrorMessage component="span" name="email" />
// --> {touched.email && error.email ? <span>{error.email}</span> : null}
<ErrorMessage component={Custom} name="email" />
// --> {touched.email && error.email ? <Custom>{error.email}</Custom> : null}
<ErrorMessage name="email" />
// This will return a string. React 16+.
// --> {touched.email && error.email ? error.email : null}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mamod |
Solution 2 | maxim.saharov |
Solution 3 | Liki Crus |