Knowledge.ToString()

ReactJS : Generic OnChange Event Handler for TextBox in Typescript

If you have a ReactJS component with multiple textboxes, you don’t want to create multiple event handlers for updating state.

Here is a way to use a generic OnChange event handler for all textboxes.

import React from "react";

interface RegistrationPageState {
    firstName: string,
    lastName: string
}

export default class RegistrationPage extends React.Component<{}, RegistrationPageState> {
    constructor(props: {}) {
        super(props);
        this.state = {
            firstName: '',
            lastName: ''
        };
    }
    textFieldOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.setState(({[e.target.name]: e.target.value} as unknown) as RegistrationPageState);
    }
    
    render(): React.ReactNode {
        return <form className="row d-none1">
            <input type="text" className="form-control" id="firstName" name="firstName" value={this.state.firstName} onChange={this.textFieldOnChange} />
            <input type="text" className="form-control" id="lastName" name="lastName" value={this.state.lastName} onChange={this.textFieldOnChange} />
        </form>;
    }
}

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *