Newbie to react. I would like to find out how to get the name of a input inorder to place in a method parameter.
<div >
<FormGroup style={{ width: "400px" }}>
<h3>Enter Barcode</h3>
<InputGroup className="mb-4">
<InputGroupAddon addonType="prepend">
<InputGroupText>
Barcode:
</InputGroupText>
</InputGroupAddon>
<Input type="text" name="**BarcodeNUmber**" onChange={(e) => { this.onChangeInput(e) }} />
</InputGroup>
</FormGroup>
<Button onClick={() =>this.onProductSearch(**BarcodeNUmber**)} color="primary" type="button">
<span className="btn-inner--text">Confirm</span>
</Button>
</div>
CodePudding user response:
I usually do not use class components with react but here we go. Changes:
- Button is within FormGroup
- onSubmit added to FormGroup
- Button type to "submit"
- using value of input instead of name.
- state controls input value
App.js
import React from "react";
class App extends React.Component {
state = { barcodeNumber: null };
onProductSearch(barcodeNumber) {
///do what you want
}
onSubmit(event) {
event.preventDefault();
this.onProductSearch(this.state.barcodeNumber);
}
render() {
return (
<div>
<FormGroup onSubmit={this.onSubmit} style={{ width: "400px" }}>
<h3>Enter Barcode</h3>
<InputGroup className="mb-4">
<InputGroupAddon addonType="prepend">
<InputGroupText>Barcode:</InputGroupText>
</InputGroupAddon>
<Input
type="text"
value={this.state.barcodeNumber}
onChange={(e) => {
this.setState({barcodeNumber: e.target.value);
}}
/>
</InputGroup>
<Button color="primary" type="submit">
<span className="btn-inner--text">Confirm</span>
</Button>
</FormGroup>
</div>
);
}
}
CodePudding user response:
Create a function that handles the onChange
and extract the value from the event target.
export default function App() {
const handleChange = (e) => {
console.log(e.target.name, ":", e.target.value);
}
return (
<div >
<FormGroup style={{ width: "400px" }}>
<h3>Enter Barcode</h3>
<InputGroup className="mb-4">
<InputGroupAddon addonType="prepend">
<InputGroupText>
Barcode:
</InputGroupText>
</InputGroupAddon>
<Input type="text" name="**BarcodeNUmber**" onChange={handleChange} />
</InputGroup>
</FormGroup>
<Button onClick={() =>this.onProductSearch(**BarcodeNUmber**)} color="primary" type="button">
<span className="btn-inner--text">Confirm</span>
</Button>
</div>
);
}
CodePudding user response:
Access it from the event
object:
onChangeInput(e) {
console.log(e.target.name);
}