I am trying to get a simple form working in React but I can't seem to get it working. I am also using react-bootstrap
for my GUI components.
I have a component called Inventory
that holds the form:
class Inventory extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
'upc' : ''
}
}
handleChange(event) { this.setState({'upc' : event.target.value }); }
handleSubmit(event) {
// Do some stuff
}
render() {
return (
<Container fluid>
<h1>Inventory Page</h1>
<Row>
<Col>
<Form onSubmit={this.handleSubmit}>
<Form.Group className="mb3" controlId="invUpcForm">
<Form.Label>UPC</Form.Label>
<Form.Control type="text" placeholder="123456789012" />
<Form.Text value={this.state.upc} onChange={this.handleChange} className="text-muted">
Ensure the field is focused, and scan the barcode.
</Form.Text>
</Form.Group>
<Button variant="primary" type="submit">Submit</Button>
</Form>
</Col>
</Row>
</Container>
);
}
}
However, whenever I enter any text into the Input field, handleChange
never gets called despite the value of the field changing. If I submit the field, checking the value of upc
in state shows it is empty ''
.
What am I doing wrong?
CodePudding user response:
According to this example from the react-bootstrap docs, you should be attaching your value
and onChange
props to the <Form.Control />
component, not <Form.Text />
. Form text is for help text, while the form controls handle the actual input elements.
CodePudding user response:
You gotta change like this.
render() {
return (
<Container fluid>
<h1>Inventory Page</h1>
<Row>
<Col>
<Form onSubmit={this.handleSubmit}>
<Form.Group className="mb3" controlId="invUpcForm">
<Form.Label>UPC</Form.Label>
<Form.Control
type="text"
placeholder="123456789012"
value={this.state.upc}
onChange={this.handleChange}
/>
<Form.Text className="text-muted">
Ensure the field is focused, and scan the barcode.
</Form.Text>
</Form.Group>
<Button variant="primary" type="submit">Submit</Button>
</Form>
</Col>
</Row>
</Container>
);
}
It is because Form.Control is a real input component, and Form.Text component is just a simple div/span to render text. You can check it by inspecting element in chrome browser.