React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
To get the value of an input field with React, first, we set the inputted value to a state.
Then we get the latest value from the state.
For instance, we can write:
class InputForm extends React.Component {
constructor(props) {
super(props);
this.state = {
val: ''
};
}
render() {
return (
//...
<input value={this.state.val} onChange={evt => this.updateInputValue(evt)}/>
//...
);
},
updateInputValue(evt) {
this.setState({
val: evt.target.value
});
}
});
We created the updateInputValue
method which calls setState
to set the value of the input field as the value of the val
state.
Then we pass that into the onChange
prop.
The value
prop has the this.state.val
which we set.
With function components, we use the useState
hook to set the value and retrieve it.
For instance, we can write:
import { useState } from 'react';
function InputForm() {
const [val, setVal] = useState('');
return (
<div>
<input value={val} onInput={e => setVal(e.target.value)}/>
</div>
);
}
We called the useState
function with the initial value of the input.
Then we passed a function to the onInput
prop to run it to set the value to the val
state when whenever something is entered.
Then we get the latest inputted value with the val
variable.
#technology #javascript #software-development #web-development #programming