I'm coding a ReactJS class with Typescript and Material-ui, in a .tsx file. In one of my custom components, I want to create a reference to one of the components that I use in my custom component.
export class MyTextField extends React.Component<MyProps, MyState> { private refTextField: React.RefObject<TextField>; constructor(props: MyProps) { super(props); this.refTextField = React.createRef(); } render(): JSX.Element { const { id, label, value: defaultValue } = this.props; const { value } = this.state; const element = ( <TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} /> ); return element; } }
During compilation, I get an error on the declaration of my reference:
'TextField' refers to a value, but is being used as a type here. TS2749
I tried to put "typeof TextField" in my declaration, but I have another message, when valuing the ref property in my render :
Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type '((instance: HTMLDivElement | null) => void) | RefObject | null | undefined'. Type 'RefObject<(props: TextFieldProps) => Element>' is not assignable to type 'RefObject'. Type '(props: TextFieldProps) => Element' is missing the following properties from type 'HTMLDivElement': align, addEventListener, removeEventListener, accessKey, and 238 more. TS2322
Any ideas ? thank you so much
At the end of the day, the only difference between TypeScript and JavaScript React project is that its file extension ends with . tsx and the other ends with . js .
TypeScript is a programming language developed by Microsoft. It is a typed superset of JavaScript, and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live. You can learn more about using TypeScript with React here.
React is a “JavaScript library for building user interfaces”, while TypeScript is a “typed superset of JavaScript that compiles to plain JavaScript.” By using them together, we essentially build our UIs using a typed version of JavaScript.
Once the object/instance is made, and we want to access the properties of class among themselves we use this keyword. In react object creation is done by below syntax <Foo /> That when the component is being called. Now in constructor by using the code this.
Make sure you're on a .tsx
file and not a .ts
file
change .ts
file to .tsx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With