Use react-input-mask with antd in react-final-form - reactjs

I would like to use react-input-mask with Ant Design Input in react-final-form. In order to use antd with react-final-form I also had to install redux-form-antd. So the file looks like this:
import React from "react";
import ReactDOM from "react-dom";
import { Button } from "antd";
import { Form, Field } from "react-final-form";
import InputMask from "react-input-mask";
import { TextField } from "redux-form-antd";
import "antd/dist/antd.css";
const onSubmit = async values => {
window.alert(JSON.stringify(values, 0, 2));
};
const Input = props => <InputMask {...props} />;
function App() {
return (
<Form
onSubmit={onSubmit}
render={({ handleSubmit, values }) => (
<form onSubmit={handleSubmit}>
<Field
name="mask"
parse={value =>
value
.replace(/\)/g, "")
.replace(/\(/g, "")
.replace(/-/g, "")
.replace(/ /g, "")
}
render={({ input, meta }) => (
<div>
<label>mask phone</label>
<Input mask="+7 (999) 999-99-99" {...input} />
{meta.touched && meta.error && <span>{meta.error}</span>}
</div>
)}
/>
<Field
name="antd"
component={TextField}
label="antd phone"
placeholder="Phone"
/>
<Button className="submit-button" type="primary">
Send
</Button>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here is a codesandbox example.
I could only get to work a regular input with an InputMask (input 1) or an antd input without a mask (input 2).
How can I add an InputMask to antd input?

I've managed to use react-input-mask with antd and react-final-form without any external libraries.
Here is my component:
import React from "react";
import InputMask from "react-input-mask";
import { Input } from "antd";
import FormItem from "antd/lib/form/FormItem";
const MaskInput = props => {
const { disabled, mask, label, meta, required } = props;
return (
<FormItem
label={label}
validateStatus={
meta.touched ? (meta.error ? "error" : "success") : undefined
}
help={meta.touched ? (meta.error ? meta.error : undefined) : undefined}
hasFeedback={meta.touched ? true : false}
required={required}
>
<InputMask
mask={mask}
disabled={disabled}
autoComplete="off"
{...props.input}
>
<Input />
</InputMask>
</FormItem>
);
};
export default MaskInput;
Then it is passed to the component prop of the Field:
<Field
name="phone"
label="Phone"
component={MaskInput}
mask="+7 (999) 999-99-99"
required
/>
Here is the link to the codesandbox example.

I've never used either of those libraries, but you might want to check out using format-string-by-pattern with react-final-form's built-in parsing and formatting functionality to achieve a similar thing.
I bet you could throw redux-form-antd components into here pretty easily...

Related

Input value is showing undefined (reading 'value') while using rsuite library

It is basically rsuite#4.10.2 version
const [user, setuser] = useState('')
<InputGroup>
<Input type='text' value={user} onChange={e=>{setuser(e.target.value)}} id="user"/>
<InputGroup.Button>
<Icon icon="user" />
</InputGroup.Button>
</InputGroup>
also i have provided with the error image just look this out
enter image description here
rsuite library return the value directly in the onChange function.
So, instead:
onChange={e=>{setuser(e.target.value)}}
You should write
onChange={value=>{setuser(value)}}
This is a class that I have written with rsuite / bootstrap and basic input. You can see the difference and copy/paste the part that you want.
import React, { useState } from 'react';
import { InputGroup, Input } from 'rsuite';
import InputGroupBoostrap from 'react-bootstrap/InputGroup';
import FormControlBoostrap from 'react-bootstrap/FormControl';
const Question2 = () => {
const [user, setUser] = useState('example');
return (
<>
{/* rsuite */}
<InputGroupBoostrap>
<Input type='text' value={user} onChange={value=>{ setUser(value)}} id="user"/>
<InputGroup.Button>
Button
</InputGroup.Button>
{/* Bootstrap */}
</InputGroupBoostrap>
<InputGroupBoostrap>
<InputGroupBoostrap.Text>User 1</InputGroupBoostrap.Text>
<FormControlBoostrap value={user} onChange={(e) => { setUser(e.target.value); }} placeholder="user" />
</InputGroupBoostrap>
{/* input */}
<div>
<span>User 2</span>
<input value={user} onChange={(e) => { setUser(e.target.value); }}/>
</div>
</>
);
}
export default Question2;
I hope I've helped

MUI v5: How can I auto focus form inputs with errors?

I am trying to make my form accessible.
Here is my sandbox link: https://codesandbox.io/s/typescript-material-ui-textfield-forked-0xh13?file=/src/App.tsx
My requirements are the following:
Upon submitting a form with validation errors, the 1st input with an error should be focused
Exactly like this form: https://a11y-guidelines.orange.com/en/web/components-examples/forms/
Is there an option in material ui to achieve this?
This is my code:
import React from "react";
import TextField from "#mui/material/TextField";
import { Form, Field } from "react-final-form";
const required = (value: string) =>
value ? undefined : "This field cannot be blank";
const App = () => (
<Form
onSubmit={(form_data) => console.log(form_data)}
render={({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit}>
<Field
name="line1"
validate={required}
render={({ input, meta }) => (
<TextField
{...input}
placeholder="Required"
label="Required"
helperText={meta.error}
error={meta.touched && meta.error}
/>
)}
/>
<Field
name="line2"
render={({ input, meta }) => (
<TextField
{...input}
placeholder="Optional"
label="Optional"
helperText={meta.error}
error={meta.touched && meta.error}
/>
)}
/>
<button onClick={handleSubmit}>Save</button>
</form>
)}
/>
);
export default App;
I ended up using a plugin for react-final-form called final-form-focus. I don't think there's anything for MUI
https://codesandbox.io/s/typescript-material-ui-textfield-forked-vep9e?file=/src/App.tsx

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.
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>
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>
You can use component props with your custom classes in ErrorMessage.
Formik docs
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}

Unable to make the Checkbox work with redux-form and react-semantic-ui

I'm trying to use redux-form with react-semantic-ui and is having trouble with the Checkbox component. The Checkbox is not being checked. I've followed the example from the redux-form documentation, but no luck. Here's the Code snippet :
renderCheckBox = ({ input, label }) => {
console.log(input.value);
return (
<Form.Field>
<Checkbox
label={label}
checked={input.value ? true : false}
onChange={input.onChange}
/>
</Form.Field>
);
};
<Field
name="activated"
label="Activate?"
component={this.renderCheckBox}
/>
The output of console.log(input.value) is empty.
Reusable redux form checkbox with semantic ui
import React from 'react';
import { object } from 'prop-types';
import { Field } from 'redux-form/immutable';
import { Checkbox as CheckboxUI } from 'semantic-ui-react';
const Checkbox = ({
input: { value, onChange, ...input },
meta: { touched, error },
...rest
}) => (
<div>
<CheckboxUI
{...input}
{...rest}
defaultChecked={!!value}
onChange={(e, data) => onChange(data.checked)}
type="checkbox"
/>
{touched && error && <span>{error}</span>}
</div>
);
Checkbox.propTypes = {
input: object.isRequired,
meta: object.isRequired
};
Checkbox.defaultProps = {
input: null,
meta: null
};
export default props => <Field {...props} component={Checkbox} />;
How to use?
import Checkbox from './Checkbox';
<form>
...
<Checkbox name="example" />
...
</form>
If you want to know whether the checkbox is checked or not, you have to use
onChange={(e, { checked }) => input.onChange(checked)}
instead of
onChange={input.onChange}
Here's a working example

React + Bootstrap + Redux value not working in form

I'm defining a form in React with Bootstrap and Redux with the following code:
import React from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock, Button } from 'react-bootstrap';
import { connect } from 'react-redux';
import './actions';
const _c = component => connect(s => s)(component);
const FieldGroup = ({ id, label, help, ...props }) => {
return (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
};
const LoginForm = _c(React.createClass({
render() {
return (
<form>
<FieldGroup
id="loginText"
type="text"
label="Text"
placeholder="Email"
value={this.props.user.email ? this.props.user.email[0] : ''}
/>
<FieldGroup
id="loginPassword"
label="Password"
type="password"
/>
<Button bsStyle="primary" bsSize="large">Login</Button>
</form>
);
}
}));
This works, and the value appears in the "Username" field, but it's not editable. I tried changing value={this.props.user.email ? this.props.user.email[0] : ''} to defaultValue={this.props.user.email ? this.props.user.email[0] : ''} and that makes it editable, but the default value never appears. What am I doing wrong?
(I would comment but I don't have 50 rep yet)
Sounds like your initial value may be undefined. Can you console.log(this.props.user.email[0]) and see that value?

Resources