Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript types for React checkbox events and handlers?

I'm building something like this React example in Typescript. The goal is to have a parent that has a state, and it creates several stateless child components that pass their clicks back to the parent.

Since the example is in Javascript I have no idea what the types of the input box events and the onChange handlers are...? I've tried several options like React.MouseEvent<HTMLInputElement>, but that's just guesswork...

Parent component create imageRows and pass the handler:

render() {   <div>     <ImageRow key={el.url} onChange={this.onChange}/>   </div>  }  // what should the type of e be?  onChange(e:any){  } 

And the ImageRow component

export interface ImageRowProps {    genre: Array<number>   url: string   onChange : any // what is the type of the callback function? }  export class ImageRow extends React.Component<ImageRowProps> {   render() {     return <div className="imagerow">         <input type="checkbox" key={index} onChange={this.props.onChange} defaultChecked={(num == 1)}/>     </div> } 

EDIT

The similar question only shows the event type, not the handler type. When I change the event type:

onChange(e: React.FormEvent<HTMLInputElement>){     console.log(e.target.value) } 

I get this error:

Property 'value' does not exist on type 'EventTarget'. 
like image 491
Kokodoko Avatar asked Aug 13 '17 21:08

Kokodoko


People also ask

How do you handle a checkbox event in React?

In React, the best way to do this is via the useState hook. This is different from normal JavaScript because we are unable to access the value of the checkbox directly from its DOM component: /* Create a checkbox functional component. Toggle the text of a paragraph with the checkbox using the 'useState' hook.

What is the type of click event in TypeScript?

The onClick event occurs when an element is clicked. This element can be a button, a div element, an image, etc. This article walks you through a couple of different examples of handling the onClick event in a React app that is written in TypeScript.

What is the data type of React event?

React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .


2 Answers

When in doubt let it infer it for you by using an arrow in position e.g.

enter image description here

Answer

In your case e is React.ChangeEvent<HTMLInputElement>.

like image 167
basarat Avatar answered Oct 12 '22 17:10

basarat


In our application,

console.log(event.target.value); // Not Working (Blank value)

console.log(event.target.checked); // Working Fine ( true / false )

//../src/components/testpage2/index.tsx  import * as React from 'react'; import {  TestInput } from '@c2/component-library';  export default class extends React.Component<{}, {}> {     state = {                 model: {                     isUserLoggedIn: true                 }                         };      onInputCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {         console.log(event.target.value); // Not Working         console.log(event.target.checked); // Working          const field = event.target.name;         const model = this.state.model;               model[field] = event.target.checked;          return this.setState({model: model});     };      render() {         return (             <div>                 <TestInput name="isUserLoggedIn" label="Is User LoggedIn : " type="checkbox" onChange={this.onInputCheckboxChange} />             </div>         );     } }  //=============================================================//  import * as React from 'react'; //import * as cs from 'classnames';  export interface TestInputProps extends React.HTMLAttributes<HTMLInputElement> {     name: string;     label: string;     onChange: React.ChangeEventHandler<HTMLInputElement>;     placeholder?: string;     value?: string;     type?: string;     error?: string;     className?: string; }  export const TestInput : React.SFC<TestInputProps> = ({ name, label, onChange, placeholder, value, type, className, error, ...rest }) => {     let wrapperClass:string = 'form-group';     if (error && error.length > 0) {       wrapperClass += " " + 'has-error';     }      return (         <div className={wrapperClass}>             <label htmlFor={name}>{label}</label>             <div className="field">                 <input                 type={type}                 name={name}                 className="form-control"                 placeholder={placeholder}                 value={value}                 onChange={onChange}/>                 {error && <div className="alert alert-danger">{error}</div>}             </div>         </div>     ); }  TestInput.defaultProps ={     type: "text" } 
like image 32
Thulasiram Avatar answered Oct 12 '22 18:10

Thulasiram