Perform HTML Input Validation on React Button Click - javascript

This is a simplified scenario.
I have a form with a required input field and a button. The button has an onClick React handler and is of type "button". I want the browser to check the HTML fields and do some initial validation (like it would do if no React were involved and the button were of type "submit"). I imagine I should do something in the handler function, but I am not sure what.
A few things I tried:
Changing the button to type "submit" does perform the check, but also calls the handler, which does not know whether the check succeeded or failed
Adding the handler on the form instead works, but makes the real example harder to maintain because I have a lot of buttons
Thank you
<div id="app"></div>
class MyClass extends React.PureComponent {
render() {
return (
<form action="#">
<input type="text" required/>
<button type="button" onClick={e => this.handle(e)}>Press</button>
</form>
)
}
handle(event) {
// What should I do here?
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))
https://jsfiddle.net/89wr3ot4/

It looks like form has a checkValidity() and reportValidity() API. The answer then becomes
class MyClass extends React.PureComponent {
render() {
return (
<form action="#" ref={this.formRef}>
<input type="text" required/>
<button type="button" onClick={e => this.handle(e)}>Press</button>
</form>
)
}
handle(event) {
const form = this.formRef.current;
if (!form.checkValidity()) {
form.reportValidity()
return
}
// Everything else
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))

You need to create state for input value
const [inputValue, setInputValue] = useState(''); //for functional component
const inputHandler = (event) => setInputValue(event.target.value);
then
<input type='text' value={inputValue} onChange={inputHandler} />
and check in your 'handler' function what you want.
handle(event) {
if (inputValue.length > 0) //do what you want...
}

Following is working example which is modified from above jsfiddle
class MyClass extends React.Component {
state = { value: '', message: ''}
render() {
return (
<form action="#">
<input type="text" required value={this.state.value} onChange={e => this.setState({value: e.target.value})} />
<button type="button" onClick={e => this.handle(e)}>Press</button>
<p> {this.state.message }</p>
</form>
)
}
handle(event) {
// What should I do here?
const { value } = this.state;
if (value === '') {
this.setState({message: 'Invalid!, Please enter valid input'})
} else {
this.setState({message: 'Yeah!, Got Valid input'})
}
}
}
ReactDOM.render(<MyClass />, document.querySelector("#app"))

Related

My inputs start with weird values

I've created very simple form for user to sign in. Here is my code:
import React,{ Component } from 'react';
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
login:"",
pass:""
}
}
signIn = (e) =>{
e.preventDefault();
alert("in")
}
handleChange = (propertyName) => (e) => {
const state = this.state;
const newState = {
...state,
[propertyName]: e.target.value
};
this.setState(newState);
}
render() {
return (
<div className="text-center">
<form onSubmit={this.signIn}>
<input type="text" id="login" onChange={this.handleChange('login')} value={this.state.login} placeholder="login"/>
<br />
<input type="password" id="pass" onChange={this.handleChange('pass')} value={this.state.pass} placeholder="pass"/>
<br />
<input type="submit" value="sign in" disabled={((this.state.login == "") && (this.state.pass == ""))
? true
: false}/>
</form>
</div>
);
}
}
export default SignIn;
For some reason every time I start my app these inputs already have some text inside. "login" always have "localhost" and "pass" contains some random numbers and letters. Can someone explain me where are these values comming from?
These fields are auto-populated by browser. See explanation here: https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
Also you might be interested in this question of how people fighting with it :)
Chrome Browser Ignoring AutoComplete=Off

React.js Expected onSubmit listener to be a function, instead got type boolean

Can someone please tell me what the hell I am doing wrong here? I am pretty new to React, and everything I have read says that this should work. I am trying to call the function "addItem" when the form is submitted, however the console.log throws the error "Expected onSubmit listener to be a function, instead got type boolean" on page load. Thanks!
import React, { Component } from 'react';
import App from "./App"
import List from "./List"
class AddTodo extends Component{
constructor(){
super();
this.state = {
items: []
}
}
addItem(e){
var itemArray = this.state.items;
itemArray.push({
text: this._inputElement.value,
key: Date.now()
})
this.setState({
items: itemArray
})
this._inputElement.value = "";
console.log(itemArray)
e.preventDefault()
}
render(){
return(
<div className="box-wrapper">
<form onSubmit={this.addItem.bind(this)}>
<input href={(a) => this._inputElement = a} placeholder={this.props.placeHolder} type="text"></input>
<button type="submit">Submit</button>
</form>
<List entries={this.state.items} />
</div>
)
}
}
export default AddTodo;
Try changing your render and addItem to something like this:
addItem(e){
e.preventDefault();
{/* add the rest of the function here */}
}
render(){
return(
<div className="box-wrapper">
<form onSubmit={this.addItem.bind(this)}>
<input
href={(a) => this._inputElement = a}
placeholder={this.props.placeHolder}
type="text"
/>
<button type="submit" onClick={this.addItem.bind(this)}>Submit</button>
</form>
<List entries={this.state.items} />
</div>
)
}
I made two important changes:
Added e.preventDefault(); to the addItem method, which will prevent default behavior.
Added an onClick handler to the "submit" button, with the addItem method passed in as the target executable.
First have to remove event.preventDefault .It is restricting the default behaviour of the webpage.Add a onClick event listener to the submit so that the function executes on button click.
`import React, { Component } from 'react';
import App from "./App"
import List from "./List"
class AddTodo extends Component{
constructor(){
super();
this.state = {
items: []
}
}
addItem(e){
var itemArray = this.state.items;
itemArray.push({
text: this._inputElement.value,
key: Date.now()
})
this.setState({
items: itemArray
})
this._inputElement.value = "";
console.log(itemArray)
// e.preventDefault(); remove this prevent default
}
render(){
return(
<div className="box-wrapper">
<form onSubmit={this.addItem.bind(this)}>
<input href={(a) => this._inputElement = a} placeholder={this.props.placeHolder} type="text"></input>
<button type="submit" onClick={this.addItem.bind(this)}>Submit</button>
</form>
<List entries={this.state.items} />
</div>
)
}
}
export default AddTodo;`
I am not getting any error. But you should put the preventDefault at the top of the addItem, this will prevent from page reload. There is better way to handle the input value by assigning ref attribute to input and accessing via this.refs.refName.
addItem(e) {
e.preventDefault(); //To prevent the page reload on submit
var itemArray = this.state.items;
itemArray.push({
text: this.refs.inputElement.value
});
this.refs.inputElement.value = ""; // clearing the value
}
render() {
return(
<div>
<form onSubmit={this.addItem.bind(this)} >
<input ref="inputElement" placeholder={this.props.placeHolder} type="text"/>
<button type="submit">Submit</button>
</form>
{
this.state.itemArray.map((item) => {
return(<span>{item}</span>)
})
}
</div>
);
}

How to disable button in React.js

I have this component:
import React from 'react';
export default class AddItem extends React.Component {
add() {
this.props.onButtonClick(this.input.value);
this.input.value = '';
}
render() {
return (
<div className="add-item">
<input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
<button disabled={!this.input.value} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
</div>
);
}
}
I want the button to be disabled when input value is empty. But the code above doesn't work. It says:
add-item.component.js:78 Uncaught TypeError: Cannot read property 'value' of undefined
pointing to disabled={!this.input.value}. What can I be doing wrong here? I'm guessing that perhaps ref isn't created yet when render method is executed. If, so what is the workararound?
Using refs is not best practice because it reads the DOM directly, it's better to use React's state instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
You can use setState together with an onChange event listener to render the component again every time the input field changes:
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
Here's a working example:
class AddItem extends React.Component {
constructor() {
super();
this.state = { value: '' };
this.onChange = this.onChange.bind(this);
this.add = this.add.bind(this);
}
add() {
this.props.onButtonClick(this.state.value);
this.setState({ value: '' });
}
onChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<div className="add-item">
<input
type="text"
className="add-item__input"
value={this.state.value}
onChange={this.onChange}
placeholder={this.props.placeholder}
/>
<button
disabled={!this.state.value}
className="add-item__button"
onClick={this.add}
>
Add
</button>
</div>
);
}
}
ReactDOM.render(
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,
document.getElementById('View')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
In HTML,
<button disabled/>
<button disabled="true">
<button disabled="false">
<button disabled="21">
All of them boils down to disabled="true" that is because it returns true for a non-empty string.
Hence, in order to return false, pass a empty string in a conditional statement like this.input.value ? "true" : "".
render() {
return (
<div className="add-item">
<input
type="text"
className="add-item__input"
ref={(input) => this.input = input}
placeholder={this.props.placeholder}
/>
<button
disabled={this.input.value ? "true" : ""}
className="add-item__button"
onClick={this.add.bind(this)}
>
Add
</button>
</div>
);
}
Here is a functional component variety using react hooks.
The example code I provided should be generic enough for modification with the specific use-case or for anyone searching "How to disable a button in React" who landed here.
import React, { useState } from "react";
const YourComponent = () => {
const [isDisabled, setDisabled] = useState(false);
const handleSubmit = () => {
console.log('Your button was clicked and is now disabled');
setDisabled(true);
}
return (
<button type="button" onClick={handleSubmit} disabled={isDisabled}>
Submit
</button>
);
}
export default YourComponent;
There are few typical methods how we control components render in React.
But, I haven't used any of these in here, I just used the ref's to namespace underlying children to the component.
class AddItem extends React.Component {
change(e) {
if ("" != e.target.value) {
this.button.disabled = false;
} else {
this.button.disabled = true;
}
}
add(e) {
console.log(this.input.value);
this.input.value = '';
this.button.disabled = true;
}
render() {
return (
<div className="add-item">
<input type="text" className = "add-item__input" ref = {(input) => this.input=input} onChange = {this.change.bind(this)} />
<button className="add-item__button"
onClick= {this.add.bind(this)}
ref={(button) => this.button=button}>Add
</button>
</div>
);
}
}
ReactDOM.render(<AddItem / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You shouldn't be setting the value of the input through refs.
Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components
In a nutshell
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />
Then you will be able to control the disabled state by using disabled={!this.state.value}
very simple solution for this is by using useRef hook
const buttonRef = useRef();
const disableButton = () =>{
buttonRef.current.disabled = true; // this disables the button
}
<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
Add
</button>
Similarly you can enable the button by using buttonRef.current.disabled = false
this.input is undefined until the ref callback is called. Try setting this.input to some initial value in your constructor.
From the React docs on refs, emphasis mine:
the callback will be executed immediately after the component is mounted or unmounted
I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.
<Button
type="submit"
disabled={
name === "" || email === "" || password === ""
}
fullWidth
variant="contained"
color="primary"
className={classes.submit}>
SignUP
</Button>

reseting or clearing an input field with reactjs

I having the following problem.
I have a react component which does a filter search on a list which is fine, but I want to clear the input field with a button, if i add a value attribute to the input field which I can set in the setState but then it stops the onChange from working as it does the filter search on the list:
I've created the following but this still doesn't work.
<input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />
<button className="uk-button uk-width-1-1" onClick="React.findDOMNode(this.refs.form).reset()"><i className="uk-icon-undo"></i></button>
set the value to empty as
handleClick = () => {
ReactDOM.findDOMNode(this.refs.form).value = "";
}
and yes onClick expects a function or a value not a string. Also React.findDOMNode() is deprecated. You should use ReactDOM.findDOMNode();
class Hello extends React.Component {
handleChange = (e) => {
}
handleClick = () => {
ReactDOM.findDOMNode(this.refs.form).value = "";
}
render() {
return (
<div>
<input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />
<button className="uk-button uk-width-1-1" onClick={this.handleClick}><i className="uk-icon-undo"></i>click</button>
</div>
)
}
}
ReactDOM.render(<Hello />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
Also Its a better idea to use state and change the state for input value.
as
class Hello extends React.Component {
constructor() {
super()
this.state = {
valueAttr : ''
}
}
handleChange = (e) => {
this.setState({valueAttr: e.target.value});
}
handleClick = () => {
this.setState({valueAttr: ''})
}
render() {
return (
<div>
<input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" value = {this.state.valueAttr} onChange={this.handleChange} />
<button className="uk-button uk-width-1-1" onClick={this.handleClick}><i className="uk-icon-undo"></i>click</button>
</div>
)
}
}
ReactDOM.render(<Hello />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
I personally prefer the second approach. But you can do it in whichever way you feel comfortable.
Here onClick="React.findDOMNode(this.refs.form).reset()" you are assigning string to onClick value of button, not a function, if you want to assign a function it should look like onClick={React.findDOMNode(this.refs.form).reset}" or onClick={() => React.findDOMNode(this.refs.form).reset()}
Next, if i recall correctly, findDOMNode is deprecated in React, so you should use ReactDOM for this.
And last, I doubt there is reset method present, so I think you should try mutating input value directly.
Try this
onClick={() => this.refs.form.value = ''}
Just use:
this.refs.form.getInputNode().value = '';
Should do the trick

to call onChange event after pressing Enter key

I am new to Bootstrap and stuck with this problem. I have an input field and as soon as I enter just one digit, the function from onChange is called, but I want it to be called when I push 'Enter when the whole number has been entered. The same problem for the validation function - it calls too soon.
var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
//bsStyle: this.validationInputFactor(),
placeholder: this.initialFactor,
className: "input-block-level",
onChange: this.handleInput,
block: true,
addonBefore: '%',
ref:'input',
hasFeedback: true
});
According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.
var Input = React.createClass({
render: function () {
return <input type="text" onKeyDown={this._handleKeyDown} />;
},
_handleKeyDown: function(e) {
if (e.key === 'Enter') {
console.log('do validate');
}
}
});
Update: Use React.Component
Here is the code using React.Component which does the same thing
class Input extends React.Component {
_handleKeyDown = (e) => {
if (e.key === 'Enter') {
console.log('do validate');
}
}
render() {
return <input type="text" onKeyDown={this._handleKeyDown} />
}
}
Here is the jsfiddle.
Update 2: Use a functional component
const Input = () => {
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
console.log('do validate')
}
}
return <input type="text" onKeyDown={handleKeyDown} />
}
You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().
<input
type="text"
placeholder="Search..."
onChange={event => {this.setState({query: event.target.value})}}
onKeyPress={event => {
if (event.key === 'Enter') {
this.search()
}
}}
/>
Pressing Enter in a form control (input) normally triggers a submit (onSubmit) event on the form. Considering that you can handle it this way (having a submit button is optional if you have only one input):
const { useState } = React;
function App() {
const [text, setText] = useState("");
const [submitted, setSubmitted] = useState('');
function handleChange(e) {
setText(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
setSubmitted(text);
setText("");
}
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" value={text} onChange={handleChange} />
<input type="submit" value="add" />
</form>
submitted: {submitted}
</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://unpkg.com/react#17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17.0.2/umd/react-dom.development.js"></script>
<div id="root"></div>
Implicit form submission (submit event on Enter) is performed when:
there's a submit button
there're no submit buttons, but there's only one input
More on it here.
Alternatively you could bind your handler to the blur (onBlur) event on the input which happens when the focus is removed (e.g. tabbing to the next element that can get focus).
You can use event.key
function Input({onKeyPress}) {
return (
<div>
<h2>Input</h2>
<input type="text" onKeyPress={onKeyPress}/>
</div>
)
}
class Form extends React.Component {
state = {value:""}
handleKeyPress = (e) => {
if (e.key === 'Enter') {
this.setState({value:e.target.value})
}
}
render() {
return (
<section>
<Input onKeyPress={this.handleKeyPress}/>
<br/>
<output>{this.state.value}</output>
</section>
);
}
}
ReactDOM.render(
<Form />,
document.getElementById("react")
)
<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>
<div id="react"></div>
React users, here's an answer for completeness.
React version 16.4.2
You either want to update for every keystroke, or get the value only at submit. Adding the key events to the component works, but there are alternatives as recommended in the official docs.
Controlled vs Uncontrolled components
Controlled
From the Docs - Forms and Controlled components:
In HTML, form elements such as input, textarea, and select typically
maintain their own state and update it based on user input. In React,
mutable state is typically kept in the state property of components,
and only updated with setState().
We can combine the two by making the React state be the “single source
of truth”. Then the React component that renders a form also controls
what happens in that form on subsequent user input. An input form
element whose value is controlled by React in this way is called a
“controlled component”.
If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.
Example:
1) Bind event handler in constructor (value kept in state)
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
2) Create handler function
handleChange(event) {
this.setState({value: event.target.value});
}
3) Create form submit function (value is taken from the state)
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
4) Render
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
If you use controlled components, your handleChange function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.
Uncontrolled
From the Docs - Uncontrolled component
In most cases, we recommend using controlled components to implement
forms. In a controlled component, form data is handled by a React
component. The alternative is uncontrolled components, where form data
is handled by the DOM itself.
To write an uncontrolled component, instead of writing an event
handler for every state update, you can use a ref to get form values
from the DOM.
The main difference here is that you don't use the onChange function, but rather the onSubmit of the form to get the values, and validate if neccessary.
Example:
1) Bind event handler and create ref to input in constructor (no value kept in state)
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
2) Create form submit function (value is taken from the DOM component)
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
3) Render
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
If you use uncontrolled components, there is no need to bind a handleChange function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.
Your issue
Now, for your issue:
... I want it to be called when I push 'Enter when the whole number has been entered
If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter key will submit the form and the handleSubmit function will be fired.
Changes you need to do:
Remove the onChange call in your element
var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
// bsStyle: this.validationInputFactor(),
placeholder: this.initialFactor,
className: "input-block-level",
// onChange: this.handleInput,
block: true,
addonBefore: '%',
ref:'input',
hasFeedback: true
});
Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.
handleSubmit(event) {
// Get value of input field
let value = this.input.current.value;
event.preventDefault();
// Validate 'value' and submit using your own api or something
}
Example use of an uncontrolled component:
class NameForm extends React.Component {
constructor(props) {
super(props);
// bind submit function
this.handleSubmit = this.handleSubmit.bind(this);
// create reference to input field
this.input = React.createRef();
}
handleSubmit(event) {
// Get value of input field
let value = this.input.current.value;
console.log('value in input field: ' + value );
event.preventDefault();
// Validate 'value' and submit using your own api or something
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
You can also write a little wrapper function like this
const onEnter = (event, callback) => event.key === 'Enter' && callback()
Then consume it on your inputs
<input
type="text"
placeholder="Title of todo"
onChange={e => setName(e.target.value)}
onKeyPress={e => onEnter(e, addItem)}/>
I prefer onKeyUp since it only fires when the key is released. onKeyDown, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter key to make a network request, you don't want that to fire multiple times since it can be expensive.
// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />
handleKeyPress(e) {
if (e.key === 'Enter') {
// do whatever
}
}
Also, stay away from keyCode since it will be deprecated some time.
Example of preventing Enter from submitting a form on an input, in my case it was a google maps location autocomplete input
<input
ref={addressInputRef}
type="text"
name="event[location]"
className="w-full"
defaultValue={location}
onChange={(value) => setLocation(value)}
onKeyDown={(e) => {
if (e.code === "Enter") {
e.preventDefault()
}
}}
/>
Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.
class ParentComponent extends React.Component {
processInput(value) {
alert('Parent got the input: '+value);
}
render() {
return (
<div>
<ChildComponent handleInput={(value) => this.processInput(value)} />
</div>
)
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleKeyDown(e) {
if (e.key === 'Enter') {
this.props.handleInput(e.target.value);
}
}
render() {
return (
<div>
<input onKeyDown={this.handleKeyDown} />
</div>
)
}
}
const [value, setValue] = useState("");
const handleOnChange = (e) => {
setValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
addTodoItem(value.trim());
setValue("");
};
return (
<form onSubmit={handleSubmit}>
<input value={value} onChange={handleOnChange}></input>
</form>
);
//You can use onkeyup directly on input field
const inputField = document.querySelector("input");
inputField.addEventListener("keyup", e => {
if (e.key == "Enter") {
console.log("hello");
}
});

Categories

Resources