Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React FormControl onChange not being triggered

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading