Search code examples
javascriptreactjstypescriptreact-bootstrapreact-tsx

React TypeScript 2.3 -> typesafe React Bootstrap FormControl onChange


When using this code I'm getting the error Property 'type' does not exist on type 'EventTarget'. The same is for checked, value and name.

Following the code I can see that FormEvent inherits from SyntheticEvent that in turn has a target: EventTarget. EventTarget does not have the properties I'm after. If I instead mark the event as any (event: any) the code works flawlessly. How can I fix this? I tried with a normal Html Input and then it worked by setting the event as React.ChangeEvent<HTMLInputElement>.

handleChange(event: React.FormEvent<React.Component<ReactBootstrap.FormControlProps, {}>>) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}
...
<FormGroup controlId="Email">
    <Col componentClass={ControlLabel} sm={2}>
        Email
    </Col>
    <Col sm={10}>
        <FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event)} placeholder="Email" />
    </Col>
</FormGroup>

Working code with Input:

handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    ...
}

...

<input
name="email"
type="email"
value={this.state.email}
onChange={(event) => this.handleChange(event)} />

Solution

  • Solved it like this:

    handleChange(event: React.ChangeEvent<HTMLInputElement>) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name as any;
    
        this.setState({
            [name]: value
        });
    }
    
    ...
    
    <FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event as any)} placeholder="Email" />