I'm working on a redux-form field array. I want to get rid of any and fields buttons and have the next field generated onkeyPress 'enter'. We will be using a scanner to enter the fields and I can code in a return on the scan to render the next field. Redux form defaults enter too 'submit'. I have read several online articles about disabling it. I have followed them and still have the same issue of the 'enter' key going to submit. I'm open to any ideas on this.
class AssignDeviceForm extends Component {
constructor(props) {
super(props);
FieldArraysForm = props => {
const { handleSubmit, pristine, reset, submitting } = this.props;
return (
<div>
<Well>
<form onSubmit={handleSubmit(() => {})}>
<FieldArray name="IMEIs" component={this.renderIMEI}/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
</Well>
</div>
);
};
renderIMEI = ({ fields, meta: { touched, error, submitFailed } }) => {
if (fields.length == 0) {
fields.unshift({});
}
return(
<ul>
<h3>Scan the devices you want to assign</h3>
{fields.map((IMEI, index) => (
<li key={index}>
<button
type="button"
title="Remove Device"
onClick={() => fields.remove(index)}
/>
<h4>Device #{index + 1}</h4>
<Field
name={`${IMEI}.txtIMEI`}
type="text"
component={this.renderField}
label="IMEI"
onKeyPress={e => {
if (e.key === 'Enter')
e.preventDefault()
console.log('WAHOO!!!')
{this.renderIMEI}
}}
/>
</li>
))}
</ul>
)};
renderField = ({ input, label, type, meta: { touched, error, active } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} type={type} placeholder={label} />
{active && touched && error && <span>{error}</span>}
</div>
</div>
);
render(){
return(
<div>
{this.FieldArraysForm()}
</div>
)
}
}
One way of preventing the enter key from submitting the form would be utilizing the onkeypress
event on the form
like so:
A working (basic) example can be found here
<form onSubmit={handleSubmit(() => {})} onKeyPress={this.onKeyPress}>
<FieldArray name="IMEIs" component={this.renderIMEI}/>
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
Where the this.onKeyPress
function will check if the enter key was pressed
onKeyPress = (event) => {
if (event.key === 'Enter') {
event.preventDefault(); //<===== This stops the form from being submitted
alert("enter")
} else {
alert("not enter")
}
}
In the onKeyPress function, you can do whatever you like, please do note that the event.preventDefault()
is what's stopping the form from being submitted by pressing enter
Hope this helps !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With