The problem with displaying imask with material ui TextField - reactjs

If I enter One character and remove the focus, the Textfield breaks.
I guess mask problems
As shown in the picture
My code https://codesandbox.io/s/happy-blackwell-5sigw?file=/src/App.js:0-610
import { TextField } from "#material-ui/core";
import { IMaskMixin } from "react-imask";
import { useForm } from "react-hook-form";
const IMaskPhoneInput = IMaskMixin(({ ...props }) => {
return <TextField {...props} />;
});
export default function App() {
const {
register,
} = useForm();
return (
<div className="App">
<IMaskPhoneInput
autoFocus
fullWidth
mask={"+{7} (000) 000-00-00"}
color="primary"
label={"Телефон"}
placeholder={"+7 (950) 356-55-44"}
{...register("phone")}
/>
</div>
);
}

Have you tried including the shrink prop?
<TextField InputLabelProps={{ shrink: true }} />
This is per the documentation at https://mui.com/components/text-fields/ under limitations
Shrink
The input label "shrink" state isn't always correct. The input label is supposed to shrink as soon as the input is displaying something. In some circumstances, we can't determine the "shrink" state (number input, datetime input, Stripe input). You might notice an overlap.
To workaround the issue, you can force the "shrink" state of the label.
<TextField InputLabelProps={{ shrink: true }} /> or <InputLabel shrink>Count</InputLabel>

Related

How to change Material UI component property according to props

This is my react js code with MUI TextField and I need to apply error and helperText property when error prop has a value. default error prop value is null.
import React from 'react'
import { TextField } from '#mui/material'
const InputField = (props) => {
const { name, label, value,error=null, onChange } = props;
return (
<TextField
variant='outlined'
label={label}
name={name}
value={value}
onChange={onChange}
{...{error && {error:true,helperText:error}}}
/>
)
}
export default InputField
The error is on this line. How I figer it on MUI 5.10.9 version
{...{error && {error:true,helperText:error}}}
use error and helperText prop directly without condition. also use space character inside helperText to avoid height issue when there is no error present. https://mui.com/material-ui/react-text-field/#helper-text
<TextField
variant='outlined'
label={label}
name={name}
value={value}
onChange={onChange}
error={!!error}
helperText={error || ' '}
/>

Remove the border from TexfField

I started using #Mui for React and I used it to create the form but after I focused TextField I see the border linke on the below screen:
My code look like this:
<FormGroup>
<TextField
label="Description"
name="description"
multiline
rows={5}
fullWidth
value={data.description}
variant="standard"
onChange={onHandleChange}
/>
</FormGroup>
How remove that?
#Edit
I resolved my problem. Border around of this element appears becouse I has styles from Breeze
Normally this can be done via CSS as well.
input {
outline: none
}
You can change the styling (remove the underline) of TextField when it is focused with makeStyles using :after
In your case do the following :
import TextField from "#mui/material/TextField";
import FormGroup from "#mui/material/FormGroup";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles({
underline: {
"&&:after": {
borderBottom: "none"
}
}
});
export default function ComboBox() {
const classes = useStyles();
return (
<FormGroup>
<TextField
InputProps={{ classes }}
label="Description"
name="description"
multiline
rows={5}
fullWidth
value={data.description}
variant="standard"
onChange={onHandleChange}
/>
</FormGroup>
);
}
And if you want it with no border at all you can pass InputProps={{ disableUnderline: true }} to your TextField

Render "outlined" input when using react-text-mask with Material-UI inputs

I'm unable to figure out how to render outlined input type(one of the standard Material-UI input styles when used with text mask).
I copied the code sample from here: https://material-ui.com/components/text-fields/
But it only gives a sample for regular(underlined) input but nothing for outlined.
This is what i'm trying to do but it doesnt work:
const ExpirationMask = props => {
const { inputRef, ...other } = props
return <MaskedInput
{...other}
ref={ref => {inputRef(ref ? ref.inputElement : null)}}
mask={[/\d/, /\d/,'/' ,/\d/, /\d/]}
placeholderChar={'\u2000'}
/>
}
<FormControl
variant='outlined' //this doesnt work
fullWidth
>
<InputLabel>Expiration</InputLabel>
<Input
value={ccExpiration}
onChange={(e, v) => setCCExpiration(e.target.value)}
placeholder='MM/YY'
variant='outlined' //this doesnt work either
inputComponent={ExpirationMask}
/>
</FormControl>
I found a solution for it. I didn't realize that TextField is just a wrapper for the Input.
There is also another wrapper for the Input which is called OutlinedInput. So this was exactly what I ended up using:
<FormControl
fullWidth
margin='dense'
>
<InputLabel
classes={{ root: classes.expInputRoot }}
error={ccExpiration.trim().length < 5}
color='primary'>
Expiration
</InputLabel>
<OutlinedInput
value={ccExpiration}
onChange={(e, v) => setCCExpiration(e.target.value)}
label="Expiration"
placeholder='MM/YY'
error={ccExpiration.trim().length < 5}
inputComponent={ExpirationMask}
/>
</FormControl>
In doing so i encountered another problem however with an InputLabel that wasn't aligning properly(not sure if it is a bug or what), so i ended up manually changing styles for it like this:
expInputRoot: {
margin:'-8px 0 0 14px'
}

How to use react-hook-form with ant design or material UI

I'm trying to use react-hook-form library to validate a form. When I render view using ant design or material UI, it does not work correctly.
<Input name="firstName" ref={register({ required: true })} />
{errors.firstName && 'First name is required'}
Some warning happened: "Missing name at.....".
For Material-UI you can pass register through the TextField component prop inputRef (I'm also using Yup for validation schemas)
import React, { useState } from 'react';
import { Button, TextField } from '#material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';
const Form: React.FC = () => {
const schema = object().shape({
username: string().required('Username is required'),
password: string().required('Password is required'),
});
const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
const onSubmit = (data: any) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="username"
error={!!errors.username}
label="Username"
helperText={errors.username ? errors.username.message : ''}
type="email"
inputRef={register}
fullWidth
/>
<TextField
name="password"
error={!!errors.password}
label="Password"
inputRef={register}
helperText={errors.password ? errors.password.message : ''}
type="password"
fullWidth
/>
<Button
color="primary"
type="submit"
variant="contained"
fullWidth
>
Submit
</Button>
</form>
);
};
react hook form author here. React Hook Form embrace uncontrolled components and native inputs, however it's hard to avoid working with external controlled component such as React-Select, AntD and Material-UI. So I have built a wrapper component to help you integrate easier.
https://github.com/react-hook-form/react-hook-form-input
Ok you may wonder what’s the point of doing this, and what are you gettin out from react hook form with controlled components? Firstly, you still benefit from our in build validation or schema validation at your choice. Secondary this will improve your app or form performance by isolating your input state update to itself, which means ur form root can be resulted with 0 re-render even with controlled component.
Here is codesandbox example:
https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s
Hopefully those make sense and that extra component Which I have created helps you too.
On top this, i have also built a wrapper component to make things a bit easier:
import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
function App() {
const { handleSubmit, register, setValue, reset } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<RHFInput
as={<Select options={options} />}
rules={{ required: true }}
name="reactSelect"
register={register}
setValue={setValue}
/>
<button
type="button"
onClick={() => {
reset({
reactSelect: '',
});
}}
>
Reset Form
</button>
<button>submit</button>
</form>
);
}
https://github.com/react-hook-form/react-hook-form-input
update
React-hook-form v4, react-hook-form-input has been merged into the main repo and renamed to Controller.
https://react-hook-form.com/api#Controller
The latest advice for V4 is to use the built-in <Controller /> component (docs). You don't need to install the extra dependency of react-hook-form-input.
From the README.md of react-hook-form-input:
This component is now a part of React Hook Form V4, and renamed to Controller with much simpler API.
Example:
<Controller
as={<TextField />}
name="firstName"
control={control}
defaultValue=""
/>
Note that the #Bill, the author of the accepted answer, now also says that the answer is outdated and to "please use controller instead."
Using the inputRef should be enough to the TextField component and for any default value the react-hook-form (useForm) provide the defaultValue in case that you want to use some default value or material-ui has the defaultValue in their TextField API
const { register, handleSubmit, errors, watch } = useForm({ mode: 'onChange' });
<TextField
inputRef={register({ required: true })}
label="Email Address"
name="email"
type="email"
autoComplete="email"
onChange={handleUpdate}
error={errors.email}
helperText={errors.email && 'email required'}
/>
I've had 0 issues using the TextField inputRef approach that some others have mentioned.
<TextField
inputRef={register}
id="name"
name="name"
/>
I posted a full working version here: https://seanconnolly.dev/react-hook-form-material-ui

React Semantic UI - How to disable a child component based on parent

How does one disable the input box here, depending on whether a checkbox has been checked or not?
I have verified the checked property - it is in working order (shows true or false boolean values).
However, I can't seem to get the disabled property in Input to work.
Below is my code:
import React from 'react';
import { Button, Checkbox, Input, List } from 'semantic-ui-react'
import PropTypes from 'prop-types';
const CategoryCheckBox = ({ type = 'checkbox', name, mylabel, checked, onChange }) => (
<React.Fragment>
<List horizontal relaxed>
<List.Item>
<Checkbox style={{ paddingLeft:"1em", paddingBottom: "1em" }} label={mylabel} checked={checked} onChange={onChange} />
<List.Content>
<Input style={{ maxWidth:"9em", paddingLeft:"1em" }} size='mini' focus placeholder='Min' disabled={checked === true ? true : false} />
<Input style={{ maxWidth:"9em", paddingLeft:"1em" }} size='mini' focus placeholder='Max' />
</List.Content>
</List.Item>
</List>
</React.Fragment>
);
CategoryCheckBox.propTypes = {
type: PropTypes.string,
name: PropTypes.string.isRequired,
mylabel: PropTypes.string.isRequired,
checked: PropTypes.bool,
onChange: PropTypes.func.isRequired,
}
export default CategoryCheckBox;
From the main program,
The component is called with the below parameters:
<CategoryCheckBox name={item.value} mylabel={item.text} checked={this.state.checkedItems.get(item.value)} onChange={this.handleChange} />
Below is my screenshot for the component along with React debugger showing the checked value.
Any Help will be highly appreciated.
Tried to set up most of the important code - Newbie to React myself. Can't get the index.js in the working order. But it gives you a good idea of my code https://codesandbox.io/embed/2pyoxpr6rn?fontsize=14
Changes:
1- You are not assigning the name to CheckBox element in CategoryCheckBox, add name here:
<Checkbox
style={{ paddingLeft: "1em", paddingBottom: "1em" }}
label={mylabel}
// ↓↓↓↓↓↓↓↓ here
name={name}
checked={checked}
onChange={onChange}
/>
2- Add disable condition for Max input field also:
<Input
style={{ maxWidth: "9em", paddingLeft: "1em" }}
size="mini"
focus
placeholder="Max"
// ↓↓↓↓↓↓↓↓ here
disabled={!checked}
/>
3- Most importantly, You are storing data in states in App component so it needs to be a class component.
Check Working Codesandbox with all these changes.
After looking at your code the problem is with your app component. Your app component has a state and therefore cannot be a stateless functional component. Your App component should look something like this.
import React from "react";
import ReactDOM from "react-dom";
import { Checkbox, Label, Header, Card, Form, Button, Container, Icon, Step, Select, Dropdown, List } from 'semantic-ui-react';
import womensBoutiqueOptions from "./womensBoutiqueOptions";
import CategoryCheckBox from "./CategoryCheckBox";
import "./styles.css";
class App() extends React.Component {
state = {
date: new Date(),
time: '10:00',
checkedItems: new Map()
}
handleChange(e) {
const item = e.target.name;
const isChecked = e.target.checked;
this.setState(prevState => ({ checkedItems: prevState.checkedItems.set(item, isChecked) }));
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Form size="large" key="large">
<h4 className="ui dividing header">Womens Information</h4>
<Form.Group widths='equal'>
<Form.Field>
<React.Fragment>
<List horizontal >
{
womensBoutiqueOptions.map(item => (
<List.Item key={item.key}>
<List.Content>
<CategoryCheckBox name={item.value} mylabel={item.text} checked={this.state.checkedItems.get(item.value)} onChange={this.handleChange} />
</List.Content>
</List.Item>
))
}
</List>
</React.Fragment>
</Form.Field>
</Form.Group>
</Form>
</div>
)
}
);
}
Check out the react documentation for some more information on why

Resources