Passing properties to react component.Getting Error - Property 'firstName' does not exist on type 'Readonly<{}>'

Viewed 137

Be patient please, react newbie here

I'm trying to do a seemingly simple component which takes in a first and last names, allows a user to change the value and displays the updated value on button click.Just can't seem to get past these TS compile errors:

1.add-user.tsx

import * as React from "react";
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';

type addUserProps = {
    firstName: string,
    lastName: string
}

class AddUser extends React.Component {
    constructor(props: addUserProps) {

        super(props);

        this.state = {
            firstName: props.firstName,
            lastName: props.lastName,
        };

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        //'firstName' does not exist on type 'Readonly<{}>'
        //alert(this.state.firstName);
    }

    render() {
        return (
            <div>
                <TextField id="firstName" label="First Name" variant="outlined" value={this.state.firstName} />
                <TextField id="lastName" label="Last Name" variant="outlined" value={this.state.lastName}  />
                <Button variant="contained" onClick={this.handleClick}>Add Candidate</Button>
            </div>
        );
    }
}

export default AddUser

Getting the following errors:

Property 'firstName' does not exist on type 'Readonly<{}>'

Property 'lastName' does not exist on type 'Readonly<{}>'

2.Trying to call the component like this:

import * as ReactDOM from "react-dom"
import AddUser from "./lib/add-user"

ReactDOM.render(
    <div>
        <AddUser firstName="John" lastName="Doe" />
  </div>,
  document.getElementById("root2")
  
);

Getting the following error:

Severity Code Description Project File Line Suppression State Error TS2322 (TS) Type '{ firstName: string; lastName: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'firstName' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'

1 Answers

Please refer to the documentation for typing class component props

You should do

class Component extends React.Component<MyProps, MyState>
Related