Reactjs: How to add startAdornment and endAdornment into the Textfield - javascript

In my project, using Textfield to add tags. But my requirement is to add an endAdornment to pass the values to be added or edited. But I don't know how to use it, please help me to do this, give me some suggestions to fix this problem.
render() {
return (
<>
<TextField id="outlined-basic" variant="outlined"
InputProps={{
startAdornment: this.state.items.map(item => (
<Chip
key={item}
tabIndex={-1}
label={item}
onDelete={() => this.handleDelete(item)}
onClick={() => this.handleItemEdit(item)}
/>
)),
// endAdornment:
}}
ref={this.state.items}
className={"input " + (this.state.error && " has-error")}
value={this.state.value}
placeholder="Type or paste email addresses and press `Enter`..."
onKeyDown={this.handleKeyDown}
onChange={this.handleChange}
onPaste={this.handlePaste}
/>
{this.state.error && <p className="error">{this.state.error}</p>}
</>
);
}
}

Related

getting error warning in MUI TextField component with select

getting error in console MUI: children must be passed when using the TextField component with select.
<TextField
select
id="outlined-basic"
label="User Name"
name="user"
size="small"
{...teamForm.getFieldProps("user")}
error={teamForm.touched.user && teamForm.errors.user}
helpertext={teamForm.touched.user && teamForm.errors.user}
>
{list?.map((option) => (
<MenuItem key={option.username} value={option.name}>
{option.name}
</MenuItem>
))}
</TextField>
Adding some other content when no list provided might help for this:
<TextField
select
id="outlined-basic"
label="User Name"
name="user"
size="small"
{...teamForm.getFieldProps("user")}
error={teamForm.touched.user && teamForm.errors.user}
helpertext={teamForm.touched.user && teamForm.errors.user}
>
{list ? list.map((option) => (
<MenuItem key={option.username} value={option.name}>
{option.name}
</MenuItem>
)) : <div></div>}
</TextField>

Why my handleChange is not being invoked? MaterialUI

Is there something wrong with the TextField component from Material UI that I'm missing?
My handleChange simply is not getting invoked.
I can type in value in the inputs, but state of the component is not changing.
Here is the Auth component:
const Auth = () => {
const [formData, setFormData] = useState(initialFormState)
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
}
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
})
}
return (
<Container component="main" maxWidth="xs">
<Paper className={classes.paper} elevation={3}>
<form className={classes.form} onSubmit={handleSubmit}>
<Grid container spacing={2}>
<Input name="email" label="e-mail" handleChange={handleChange} type="email" />
<Input name="password" label="password" handleChange={handleChange} type={showPassword ? "text" : "password"} handleShowPassword={handleShowPassword} />
</Grid>
<Button type="submit" variant="contained" color="primary" className={classes.submit} fullWidth>
{isSignup ? "Sign up" : "Sign in"}
</Button>
</form>
</Paper>
</Container>
);
}
And the input component which is inside Auth:
const Input = ({ name, half, handleChange, type, label, autoFocus, handleShowPassword }) => {
return (
<>
<Grid item xs={12} sm={half ? 6 : 12}>
<TextField
name={name}
handleChange={handleChange}
variant="outlined"
required
fullWidth
label={label}
autoFocus={autoFocus}
type={type}
InputProps={name === "password" ? {
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={handleShowPassword}>
{type === "password" ? <Visibility/> : <VisibilityOff/>}
</IconButton>
</InputAdornment>
)
} : null}
/>
</Grid>
</>
);
}
You've to change the input attribute from handleChange to onChange
<Input name="email" label="e-mail" onChange={handleChange} type="email" />
<Input name="password" label="password" onChange={handleChange} type={showPassword ? "text" : "password"} handleShowPassword={handleShowPassword} />

TypeError: Cannot read property 'style' of null on TextareaAutosize

I am having trouble with unit snapshot testing and cant figure why.
I am getting the following error:
enter image description here
The component is actually a Form with 3 fields: Full name, Email and Note. There is also a checkbox which controls the Email and Note field in case we dont want to put that information in the form.
For the Note I am using TextareaAutosize, so that the text area is re sizable (due to requirements).
const [missingInfo, setMissingInfo] = useState(false);
const initialValues = {
fullName: '',
email: '',
note: '',
};
return (
<Formik
initialValues={initialValues}
validationSchema={object({
fullName: string().required('Must contain a full name'),
})}
onSubmit={(values, { setSubmitting }) => {
setSubmitting(true);
...
}}
>
<Form>
<Typography>Title</Typography>
<HashLink
to={{ hash: '#xxx' }}
onClick={() => toggleHash()}
>
Changed your mind?
</HashLink>
<Typography>Full name</Typography>
<Field name="fullName">
{({ field }: FieldProps) => (
<TextField
id="fullName"
variant="outlined"
type="text"
fullWidth
{...field}
/>
)}
</Field>
<ErrorMessage name="fullName">
{msg => <div className={styles.errorMessage}>{msg}</div>}
</ErrorMessage>
<FormControlLabel
control={
<Checkbox
checked={missingInfo}
onChange={() => setMissingInfo(!missingInfo)}
name="missingInfo"
/>
}
label="No info?"
/>
{!missingInfo && (
<>
<Typography>Email</Typography>
<Field name="email">
{({ field }: FieldProps) => (
<TextField
id="email"
variant="outlined"
type="text"
fullWidth
{...field}
/>
)}
</Field>
<Typography>Note</Typography>
<Field name="note">
{({ field }: FieldProps) => (
<TextareaAutosize
rowsMin={3}
className={styles.textArea}
{...field}
/>
)}
</Field>
</>
)}
<Button
variant="contained"
type="submit"
>
Apply
</Button>
</Form>
</Formik>
)
The error is as I said in the snapshot test:
test('matches snapshot', () => {
const tree = renderer
.create(
<BrowserRouter>
<MyComponent {...props} />
</BrowserRouter>,
)
.toJSON();
expect(tree).toMatchSnapshot();
});
Can someone please help?

How to handle a single form for Create and Update in React

I need some help on the form management in React. Indeed I'm currently working on a project where I would like to use one Form (Component using TextFields) to complete the Create a new User and Update an existing user actions.
I am able to create a User, and I am also able to get the form filled with existing values when I click on edit.
But as soon as I want to modify on field it automatically "re-render" the create Form.
So far here is what I've done :
In my UserList component(handle the display of Users) :
Created a variable to store the Dialog component and the UserForm (form used to create and update)
const dialogHandleUser =
<Dialog
open={openForm}
onClose={handleClose}
onEscapeKeyDown={handleClose}
aria-describedby="alert-dialog-description"
>
<UserForm
currentUser={currentUser}
onSaveForm={handleClose}
/>
</Dialog>
Used this variable in the return of my UserList Component :
return (
<div>
<Button className={classes.button} onClick={() => {handleClickAddForm({})}} variant="contained" color="primary">
<Typography className={classes.buttonText}> Ajouter un utilisateur</Typography>
{dialogHandleUser}
</Button>
<Paper className={classes.container} elevation={1}>
<TableContainer>
<Table className={classes.table}>
<TableHead className={classes.tableHead}>
<TableRow>
<TableCell className={classes.tableHeadCell}><strong>Nom</strong></TableCell>
<TableCell className={classes.tableHeadCell}><strong>Prénom</strong></TableCell>
<TableCell className={classes.tableHeadCell}><strong>Email</strong></TableCell>
<TableCell className={classes.tableHeadCell}><strong>Actions</strong></TableCell>
</TableRow>
</TableHead>
<TableBody>
{displayUsers}
{dialogDelete}
</TableBody>
</Table>
</TableContainer>
</Paper>
</div>
I am using the same "dialogHandleUser" for Create and Update
Now the UserForm component is structured like this :
function UserForm(props) {
const classes = useStyles();
const { currentUser, onSaveForm } = props;
const [newUser, setNewUser] = useState({...currentUser});
const handleChange = (event) => {
event.preventDefault();
console.log(newUser)
console.log('change value to ' + event.target.value)
if (event.target.name === 'roles') {
newUser[event.target.name] = [event.target.value]
} else {
newUser[event.target.name] = event.target.value
}
setNewUser({...newUser})
};
const handleSaveUser = async (event) => {
event.preventDefault();
// call API
try {
if (newUser.userID) {
await API.post(`/mercure/user/update/admin/${newUser.userID}`, newUser)
onSaveForm()
} else {
newUser['password'] = ''
await API.post('/mercure/auth/signup', newUser, {params: {generated: true}});
onSaveForm()
}
}
catch (e) {
alert(e)
}
}
return(
<FormControl>
<Paper className={classes.container}>
{currentUser.userID ?
<Typography variant='h2'> Modifier votre utilisateur </Typography>
:
<Typography variant="h2"> Créer un nouvel utilisateur </Typography>
}
<TextField className={classes.table}
autoFocus
label='Nom de famille'
name='lastName'
variant="outlined"
onChange={handleChange}
value={currentUser.lastName}
/>
<TextField className={classes.table}
label='Prénom'
name='firstName'
variant="outlined"
onChange={handleChange}
value={currentUser.firstName}
/>
<TextField className={classes.table}
label='Adresse Email'
name='email'
variant="outlined"
onChange={handleChange}
value={currentUser.email}
/>
<RadioGroup aria-label="Roles" name="roles" onChange={handleChange}>
<FormControlLabel value={"Administrator"} control={<Radio />} label="Administrateur" />
<FormControlLabel value={"NormalUser"} control={<Radio />} label="Utilisateur standard" />
</RadioGroup>
<RadioGroup aria-label="Roles" name="sex" onChange={handleChange}>
<FormControlLabel value={"Man"} control={<Radio />} label="Mr." />
<FormControlLabel value={"Woman"} control={<Radio />} label="mm" />
</RadioGroup>
<Button variant="contained" color="primary" onClick={handleSaveUser}> Sauvegarder </Button>
</Paper>
</FormControl>
)
}
export default UserForm;
To summarize I am able to create and update in backoffice
But the display of the modal and the form which is supposed to be conditionnal is not working..
If someone can explain me why it's not persistant it will help a lot.
Thank you

Force a disabled MI TextField to be clickable

I have a TextField that is disabled and I'm updating it with React Hooks useState by changing the value property of the TextField.
const [employee , setEmployee] = React.useState('')
<TextField
fullWidth
disabled
value={employee}
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<BackupIcon onClick={handleClick}/>
</InputAdornment>
),
}}
/>
It's only clickable on the Icon BackupIcon.
How can we make it clickable all over the TextField ?
Have you tried putting the onClick like this:
handleClick: function(e) {
this.setState({
textFieldValue: e.target.value
});
},
<TextField fullWidth
disabled
value={employee}
variant="outlined"
onChange={handleClick}
>
<BackupIcon />
<TextField />

Categories