How to prevent enter key triggering submit - reactjs

I am using Formik for a little form in a React app.
The method handleSubmit is triggered when user hits the enter key.
Is there a way to prevent that triggering?
I didn't find anything in the formik docs...
Thanks.

You could add an onKeyDown handler like this:
/**
* Stop enter submitting the form.
* #param keyEvent Event triggered when the user presses a key.
*/
function onKeyDown(keyEvent) {
if ((keyEvent.charCode || keyEvent.keyCode) === 13) {
keyEvent.preventDefault();
}
}
/**
* Sample form component.
*/
function Example() {
return (
<Formik initialValues={{ name: "" }} onSubmit={() => console.log("Submit")}>
<Form onKeyDown={onKeyDown}>
<div>
<label htmlFor="name">Name</label>
<Field id="name" name="name" type="text" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
See CodeSandbox example here.

Related

(Using React) Why is the submit button when onClick is performed using onChange events and resulting in empty string? (useState question)

Description:
The submit button calls a function called displayFields. This function then console logs the state of the input fields. The start of the input fields is listened to by onChange that sets the new state.
Before clicking the submit button the input fields when something is entered console logs the current state of the fields and then provides each string character in the console. To my understanding onChange should listen for changes but not console anything. When the button is clicked it should perform the function one time and console the current state of what is entered in fields. Instead when clicked the fields clear and then console an empty string.
I will provide my code and screen shots to help.
const GetQuote = (props) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [question, setQuestion] = useState("");
const dispFields = () => {
console.log(name + email + question);
};
/*
This is used in case prevent defualt needs used
function handleSubmit(e) {
e.preventDefault(); }
*/
return (
<React.Fragment>
<form
id="quoteForm"
//onSubmit={handleSubmit}
>
<h1 id="quoteTitle"> Quote Help Form </h1>
<p id="quotePar">
{" "}
Please provide your Name, Contact Email, and what products you would
like more information about in this form:{" "}
</p>
<label id="formName" className="Form">
Name:
<input
type="text"
name="name"
onChange={(event) => {
setName(event.target.value);
}}
/>
</label>
<label id="formEmail" className="Form">
Email:
<input
type="text"
name="email"
onChange={(event) => {
setEmail(event.target.value);
}}
/>
</label>
<br />
<label id="formQuestion" className="Form">
What products would you like to know more about:
<input
type="text"
name="help"
onChange={(event) => {
setQuestion(event.target.value);
}}
/>{" "}
</label>
<br />
<br />
<button
id="quoteSubmit"
type="submit"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick={dispFields()}
>
Submit{" "}
</button>
</form>
</React.Fragment>
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
onClick={dispFields()} is getting called on every render. If you pass it without calling it (onClick={dispFields} that should only log it to the console when the button is clicked.
You try to alter from
<
button id = "quoteSubmit"
type = "submit"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick = {
dispFields()
} >
Submit < /button>
to
<
button id = "quoteSubmit"
type = "button"
//funtion is called however seems to constantly call the useState which is used in onchange
//when submit is done returns empty string
onClick = {()=>
dispFields()
} >
Submit < /button>
Changed "button" from "submit", arrow function involved
Both solutions provided above work. Changing to example = {example} from example = {example()}. Also calling it from a arrow function also works. The issue is a node issue. What happens when the use breakpoints is set on the function, the values are console logged however after they are console logged the form refreshes and then the state refreshes so the console logs are never logged because the browser processes the value of event and clears the event at the same time. So as long as the values can be passed to the backend, the front end can remain clearing the value being rendered.

React Formik - app performs unwanted request (submit) after pressing Enter key in the input field

When I write something in the "name" field and press Enter, app performs a request, address bar in the web browser changes to http://localhost:3000/?name=something. But when I just add another input field to the form, app behaviour changes: it doesn't perform request in such case. I would like to ask:
1. Why app behaviour is dependent on the number of input fields?
2. How can I force app to not perform submit (request) when there is
only one field in the form, to act like there would be many fields?
import {Formik} from 'formik';
function App() {
return (
<div className='App'>
<Formik>
{props => (
<form>
<input type="text" name="name"/>
{/*If I uncomment the line below, the app will not perform request after pressing Enter*/}
{/*<input type="text" name="surname"/>*/}
</form>
)}
</Formik>
</div>
);
}
export default App;
I think your validation is just stoping it when you have two fields. HTML form should submit by default when you hit enter. You have an html form.
If you can, I would just remove the html form element and manually control the submit.
<Formik
initialValues={{ name: 'test' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{props => (
<>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
/>
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<button onClick={props.handleSubmit}>Submit</button>
</>
)}
</Formik>
Or just use the formik "Form" component and create a custom event handler for the enter key press.
you need to have a couple of things..
You need to have a validationSchema.
You can do this with yup, or write your own.
Inside the Formik tag, you should then add the following fields
<Formik
initialValues={{ name: "", surname: "" }}
onSubmit={(values) => console.log(values)}
validationSchema={validationSchema}>

React Forms and Events

I have a search form with a few inputs the user can enter data into and some buttons on the right hand side that toggle the search. Underneath everything is the main 'search' button. What happens when the user hits return or enter in any of the inputs is on of my toggle buttons onClick handlers always fires and I don't know why. I recreated the gist of this in fiddle/code here:
class Sample extends React.Component {
handleSubmit(e) {
e.preventDefault();
console.log('handle search called');
}
handleClick(e) {
e.preventDefault();
console.log('handleClick called');
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="filterRow">
<div className="filterColumn1">
<label style={{"display":"block"}}>
Name:
<input type="text" name="name" />
</label>
<label>
Id:
<input type="text" name="id" />
</label>
</div>
<div className="filterColumn2">
<button key="sth" onClick={this.handleClick}>
do something
</button>
</div>
</div>
<button type="submit" onClick={this.handleSubmit}>
SEARCH
</button>
</form>
);
}
}
ReactDOM.render(<Sample/>, document.getElementById('app'))
JSFiddle
Question: Why does the click handler on that button fire when you hit enter or return in the inputs? How come its not the handleSubmit which is the onsubmit of the form?
When you hit Enter this triggers your button with submit type (that's just natural behavior of forms not sure why). Your button onClick handler (handleClick) has e.preventDefault() called which prevents further bubbling of an event and that's why handleSubmit is not getting triggered.
If you change button type to type="button" then Enter will not trigger your button onClick handler.
Btw. on your example onSubmit has handleSearch as event handler but I guess you meant handleSubmit.

How to force Enter key to trigger "submit" function without need to focus an input

I'm making an app in react-redux and I want a simple feature but that's starting to look tricky to implement.
:)
I want to be able to open my webapp (I land on my login screen) and just hit enter (the browser has already saved my user and password and they are filled in in the correct input fields) and have that "enter" keystroke tigger my login function without me needing to click anywhere first to focus something.
(On a non-root component)
I've already got my password input (the last one) bound to the enter key correctly.
So pressing enter when I have the password field focused works :
handleSubmit() {
const { authenticate } = this.props;
const { tusername, tpassword } = this.state;
const credentials = {
username: tusername,
password: tpassword,
};
authenticate(credentials);
}
_handleKeyPress = (e) => {
if (e.key === 'Enter') {
this.handleSubmit();
}
};
render() {
return (
<div onKeyPress={this._handleKeyPress} >
<Card id="signin">
<CardImg top width="100%" src={rubisLogo} alt="Rubis" />
<InputGroup>
<Input
placeholder="Nom d'utilisateur"
value={this.state.tusername}
onChange={this.updateUser}
/>
</InputGroup>
<InputGroup>
<Input
placeholder="Mot de passe"
type="password"
value={this.state.tpassword}
onChange={this.updatePassword}
onKeyPress={this._handleKeyPress}
/>
</InputGroup>
<div>
<Button
id="btn"
onClick={this.handleSubmit}
to="/home">Login
</Button>
</div>
<ModalPassword class="modal" buttonLabel="Mot de passe oublié ?" />
<ModalAccount class="modal" buttonLabel="Créer un compte" />
</Card>
</div>);
}
as you can see I've tried putting it on the div but that didn't work. also I don't want a solution based on that. I want the enter-key to be a gobal fallback on this view. the user can't loose this funtionality just because he clicked somewhere.
Set the focus to the div by default using tabIndex so that the javascript event will be triggered
render() {
return (
<div onKeyPress={this._handleKeyPress} tabIndex="1" >
<Card id="signin">
..)}
You have to wrap your components with a form tag instead of a div, handle the onSubmit event, and the property type of Login button you must set it to submit.
...
handleSubmit = (e) => {
e.preventDefault(); // prevent browser behavior
// Handle submit logic
...
};
render() {
return (
<form onSubmit={handleSubmit}>
...
<Button
id="btn"
type="submit"
to="/home">Login
</Button>
</form>
);
}

I cannot clear input on submitting form

I am using reactJs coupled with redux-form.
And also using the semantic ui react library
When i want to submit my form, i don't want my page to be refreshed. Instead i want to reset my form after the submission.
Unfortunately, i can't clear my input whereas i set the state to void the value.
/** Form component **/
<Form onSubmit={handleSubmit(this.handleSubmitAction)}>
<Field name="input" component={renderTitleInput} onChangeAction={this.handleInputChange} defaultValue={this.state.input} />
<input type="submit" name="submit" />
</Form>
/** HandleSubmit function **/
handleSubmitAction = (e) => {
this.setState({input:''})
}
The field remain filled after submitting the form.
Any suggestion ? thanks
What you created is an uncontrolled component, which means that update must be handled through the DOM. To do that you need to add the refattribute to get access to the DOM element in the form submit callback. Here is the changes you need to make.
<Form onSubmit={handleSubmit(this.handleSubmitAction)}>
<Field name="input" component={renderTitleInput} onChangeAction={this.handleInputChange} defaultValue={this.state.input} ref={(input) => this.input = input} />
<input type="submit" name="submit" />
</Form>
/** HandleSubmit function **/
handleSubmitAction = (e) => {
// This can be used when using controlled component.
//this.setState({input:''})
this.input.val = '';
}
But maybe what you want is to handle it as controlled component.
I had a similar issue and I want to clear input after submit button is clicked & use the functional component. here is an example of how I reset the value of input field after submitting.
Set value of the input to state value & when state value is reset input field get reset and the field is empty.
const [cancelInput, setCancelInput] = useState('');
const inputChange = (event, data) => {
// console.log(data)
setCancelInput(data.value)
}
const handleClick = (e) => {
setCancelInput(e.target.value)
}
<Input onChange={inputChange} placeholder='Type cancel here' value={cancelInput}/>
<Button color='red' onClick={handleClick} disabled={cancelInput !== 'cancel'} loading={loading} >Cancel</Button>

Resources