TextField mui component autoFocus end of text - reactjs

Right now, autoFocus applies to the beginning of the input but I'd like to get focused on the end of the text.
export default function BasicTextFields() {
const [value, setValue] = React.useState(
"hello world. hello world. hello world"
);
return (
<Box
component="form"
sx={{
"& > :not(style)": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
>
<TextField
id="outlined-basic"
variant="outlined"
value={value}
onChange={(e) => setValue(e.target.value)}
multiline
autoFocus
/>
</Box>
);
}
Is this possible?
I tried this from this link : https://github.com/mui/material-ui/issues/12779
But this didn't work for my case.
<TextField
variant="outlined"
type="text"
id="field-comment"
name="comment"
label="Label"
placeholder="Placeholder"
onChange={(event) => setValue(event.target.value)}
inputRef={(input) => input && input.focus()}
onFocus={(e) =>
e.currentTarget.setSelectionRange(
e.currentTarget.value.length,
e.currentTarget.value.length
)}
multiline
rows={4}
value={value}
className={classes.sCommentTextField}
/>
I also tried this.
<TextField
inputRef={input => input && input.focus()}
/>
but it also didn't work.
Are there any ways that I can do this?

This works!
<TextField
variant="outlined"
type="text"
id="field-comment"
name="comment"
label="Label"
placeholder="Placeholder"
onChange={(event) => setValue(event.target.value)}
inputRef={(input) => input && input.focus()}
onFocus={(e) =>
e.currentTarget.setSelectionRange(
e.currentTarget.value.length,
e.currentTarget.value.length
)}
multiline
rows={4}
value={value}
className={classes.sCommentTextField}
/>
Remove autoFocus and add inputRef and onFocus

Related

Can we remove the calendar icon from the TextField (MUI)?

Here is my basic code to accomplish the task, but couldn't come up with any outcome
<TextField
sx={{
'&::-webkit-calendar-picker-indicator': {
display: 'none',
'-webkit-appearance': 'none',
},
}}
id="outlined-basic"
variant="outlined"
type="date"
helperText="Please select the date"
/>
Also, I did a bit research on InputProps (endAdornment) within TextField to remove the icon, but that didn't work.
You can define in the components property the icon to be null for both cases.
<TimePicker
label="Time"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
disableOpenPicker
/>
<DateTimePicker
label="Date&Time picker"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
disableOpenPicker
/>
Here is a working sandbox
I guess u r using MUIv5
(and I guess u talking about DatePicker)
In that case (as u mentioned), the icon is rendered cuz the InputProps with endAdornment is passed to the text field, if u omit that prop, there will be no icon.
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={({ InputProps, ...props }) => (
<TextField {...props} />
)}
/>

Password field showing "password is required" even after a value is passed

I am working on a login form with Next Js as frontend and uses MUI 5. The issue is that even after i pass a value to password field, when i click on login button it is showing password field is required. Also when i try to console log the username and password to test it, only username got displayed in the console. please help me to understand what mistake I am doing. Please find the login form below
Please find the code MUI code for both username and password(I am making use of a purchased theme)
<form noValidate autoComplete='off' onSubmit={handleSubmit}>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='Username'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange, onBlur } }) => (
<TextField
autoFocus
label='Username'
value={value}
onBlur={onBlur}
//onChange={onChange}
onChange={(e)=> setUsername(e.target.value)}
error={Boolean(errors.user)}
// placeholder='admin#materio.com'
/>
)}
/>
{errors.user && <FormHelperText sx={{ color: 'error.main' }}>{errors.user.message}</FormHelperText>}
</FormControl>
<FormControl fullWidth>
<InputLabel htmlFor='auth-login-v2-password' error={Boolean(errors.password)}>
Password
</InputLabel>
<Controller
name='password'
control={control}
rules={{ required: true }}
render={({ field: { value, onBlur } }) => (
<OutlinedInput
value={value}
onBlur={onBlur}
label='Password'
//onChange={onChange}
onChange={(e)=> setPassword(e.target.value)}
id='auth-login-v2-password'
error={Boolean(errors.password)}
type={showPassword ? 'text' : 'password'}
endAdornment={
<InputAdornment position='end'>
<IconButton
edge='end'
onMouseDown={e => e.preventDefault()}
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOutline /> : <EyeOffOutline />}
</IconButton>
</InputAdornment>
}
/>
)}
/>
{errors.password && (
<FormHelperText sx={{ color: 'error.main' }} id=''>
{errors.password.message}
</FormHelperText>
)}
</FormControl>

reactjs: Es6 unable to understand the syntax

I am using react hook forms and encountered this example of using Controller for material ui TextField
({ field: { ref, ...field } }) => (
<TextField
{...field}
inputRef={ref}
fullWidth
required
label="Current Password"
type="password"
margin="dense"
/>
)
What does the below mean
({ field: { ref, ...field } })
and also {...field} (what it expands to)
<TextField
{...field}
inputRef={ref}
fullWidth
required
label="Current Password"
type="password"
margin="dense"
/>
The total code is
<Controller
name="old_password"
control={control}
render={({ field: { ref, ...field } }) => (
<TextField
{...field}
inputRef={ref}
fullWidth
required
label="Current Password"
type="password"
margin="dense"
/>
)}
/>
It's jus't a regular component... Think about it like this:
const Component = (props) =>{
const {ref, ...field} = props.field
return(
<TextField
{...field}
inputRef={ref}
fullWidth
required
label="Current Password"
type="password"
margin="dense"
/>
)
}
...field is just the spreaded original field props.field with ref property subtracted. In this case necessary cause TextField expects a ref to be hold by inputRef

How to display data from html response body on textfield or textArea in material UI reactjs?

I have a form. On clicking the 'Evaluate' button, I send a post request. The response of this request is JSON, which I need to display in textField named Output.
How to display data in 'Output' textField?
I just need to display data(which is json in this case) to the text field.
My text field looks like this:
const MyTextField = ({select, values, nullable, min, max, helpertext, ...props}) => {
const [field, meta] = useField(props);
return (
<TextField
select={!!select}
variant="outlined"
margin="dense"
//{...field}
//defaultValue={meta.initialValue}
value={field.value}
error={meta.touched && meta.error}
helperText={(meta.touched && meta.error) ? meta.error : helpertext}
onChange={field.onChange}
onBlur={field.onBlur}
InputProps={{inputProps: {min: min, max: max}}}
{...props}
>
{
values && nullable && values instanceof Array && <MenuItem ><em>None</em></MenuItem>
}
{
values && values instanceof Array && values.map((value, index) => {
return <MenuItem key={value} value={value}>{value}</MenuItem>
})
}
</TextField>
);
};
and form looks like this
return (
<Container fluid className="main-content-container px-4">
<Row noGutters className="page-header py-4">
<PageTitle sm="12" title="Transformer Tester Tool" subtitle="" className="text-center"/>
</Row>
<Paper id="connPageRoot" className={classes.testerRoot}>
<Formik onSubmit={submitEvaluate} initialValues={request}>
<Form>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="json2JsonTransformationConfigDto.template"
name="json2JsonTransformationConfigDto.template"
label="JSLT template"
multiline={true}
rowsMax={4}
fullWidth={true}/>
</div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="inputs.0"
name="inputs.0"
label="Json payload to be tested"
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
<div className={classes.connPageButton}>
<Button type={"submit"} color="primary" variant="contained">Evaluate</Button> </div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="outputs.0"
name="outputs.0"
label="Output"
value={result}
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
</Form>
</Formik>
</Paper>
</Container>
);

How to clear input fields after submit in react

so i'm creating my portfolio and i am now on the final page, the contact page. I have it almost finished. I have it hooked up with emailjs and i receive emails with the message inputted as expected.
The problem i'm having is, when the form is submitted, i don't know how to clear the UI input fields. I could disregard using e.preventDefault(), however, i would like to keep that, as i want to style the page if the desired result has been achieved(message sent), or if an error has occurred. I would like to mention that i had used state for the name, email and message beforehand, however, i was unable to use the state variables in conjunction with the emailjs syntax, more specifically, with the "e.target" section. When the form is submitted, the result is the message being sent to my email, with the text inputted by the user still in the input fields.
The code is below, with some names left as hidden for privacy reasons:
import React, { useState } from 'react'
import { Box, Grid, Typography, Button} from '#material-ui/core'
import Navbar from './Navbar';
import Styles, { InputField } from './Styles'
import SendIcon from '#material-ui/icons/Send'
import emailjs from 'emailjs-com'
function Contact() {
const classes = Styles()
function sendEmail(e) {
e.preventDefault()
emailjs.sendForm('gmail', 'hidden', e.target, 'hidden')
.then((result) => {
console.log(result.text);
result.text ==="OK" ? console.log("it worked") : console.log("didnt work")
}, (error) => {
console.log(error.text);
});
}
return (
<Box component='div'>
<Navbar/>
<Grid container justify='center'>
<Box component='form' className={classes.contactContainer} onSubmit={sendEmail}>
<Typography variant='h5' className={classes.contactHead}>Contact Me</Typography>
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<InputField
id="email"
name="email"
fullWidth={true}
label="Email"
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<InputField
id="message"
name="message"
fullWidth={true}
label="Enter Message Here"
multiline
rows={8}
variant="outlined"
margin='dense'
size='medium'
/>
<br/>
<Button
type="submit"
variant='outlined'
fullWidth={true}
endIcon={<SendIcon/>}
className={classes.contactButton}>
Contact Me
</Button>
</Box>
</Grid>
</Box>
)
}
export default Contact
For the simplest way to do it in your code, use useState to declare initial value of the fields such as:
const [name, setName] = useState("");
Then you need to set the "value" param in your InputField component, eg:
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
value={name}
/>
And after receiving the result in emailjs.sendForm, use setName to reset the value of the name field, eg:
setName("")
Use the similar method for other fields.
Thank you for the answer, it helped, however did not fully fix the problem. That being said, i was able to find a solution. I used the onChange param and passed through a function which changes the state AND the value. Also, after receiving the result in emailjs.sendForm, i reset the value of all the fields.
const handleChange = (event) => {
event.target.name=="name"
? setName(event.target.value)
: event.target.name=="email"
? setEmail(event.target.value)
: event.target.name=="message"
? setMessage(event.target.value)
: console.log("error")
};
function sendEmail(e) {
e.preventDefault()
emailjs.sendForm('gmail', 'hiddenForPrivacy', e.target, 'hiddenForPrivacy')
.then((result) => {
console.log(result.text);
result.text ==="OK" ? console.log("it worked") : alert("didnt work")
setName("")
setMessage("")
setEmail("")
}, (error) => {
console.log(error.text);
});
}
The input fields now look like this:
return (
<Box component='div'>
<Navbar/>
<Grid container justify='center'>
<Box component='form' className={classes.contactContainer} onSubmit={sendEmail}>
<Typography variant='h5' className={classes.contactHead}>Contact Me</Typography>
<InputField
id="name"
name="name"
fullWidth={true}
label="Name"
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={name}
/>
<br/>
<InputField
id="email"
name="email"
fullWidth={true}
label="Email"
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={email}
/>
<br/>
<InputField
id="message"
name="message"
fullWidth={true}
label="Enter Message Here"
multiline
rows={8}
variant="outlined"
margin='dense'
size='medium'
onChange={(e) => handleChange(e)}
value={message}
/>
<br/>
<Button
type="submit"
variant='outlined'
fullWidth={true}
endIcon={<SendIcon/>}
className={classes.contactButton}>
Contact Me
</Button>
</Box>
</Grid>
</Box>

Resources