Microsoft 365 – SPFx OR react app error: Property ” does not exist on type ‘Readonly<{}>‘ while accessing state property – {this.state.property}
Hi All,
Greetings for the day !!!
Today new REACT / SPFX component issue and solution 🙂
Prerequisites:
- Make sure we have following packages are installed
- “@pnp/spfx-controls-react”
- “@fluentui/react”
npm install "@pnp/spfx-controls-react"
npm install "@fluentui/react"
Details / Background :
- Recently I started working on SPFx component and using REACT framework
- One of feature of my SPFx component is to get data which we are requesting from the user and store in list on SUBMIT button
- So to get the data we are using fluent UI control and on respective events setting the state
- Following are simple steps to demonstrate:
- Using Fluent UI control – TextField – get the input from the user
- On change event of TextField – set the state – say “frm_txtprojectname“
- On Submit button click read the value from state variable
Respective code as follows:
#importing respective controls
import {PrimaryButton, TextField } from '@fluentui/react';
export default class KnowledgeJunction extends React.Component<IKnowledgeJunctionProps, {}> {
//Initializing state
this.state = {
txt_projectname=""
}
#render method :
public render(): React.ReactElement<IAddprojectProps> {
return(
<Label>Enter text:</Label>
<TextField onChange={this.onchange.bind(this)} name="txt_projectname" value={this.state.txt_projectname}/>
<PrimaryButton text="Submit" onClick={() => this.submit()} />
);
}//render
//textfield on change event
/**
*
* @param value Change event for all text controls
* @param stateValue
*/
public onchange(e) {
//alert("change event called => " + e.target.value) ;
let change = {};
change[e.target.name] = e.target.value;
this.setState(change);
}//onchange
public async submit() {
//getting value from text field
var projectname = this.state.txt_projectname; #Here getting an error - Property 'txt_projectname' does not exist on type 'Readonly<{}>
}//submit
}#class
Issue / Cause of an error :
Property ” does not exist on type ‘Readonly<{}>
This error caused because the second parameter to the class “KnowledgeJunction ” is the type of “state” and we are passing empty object as
export default class KnowledgeJunction extends React.Component<IKnowledgeJunctionProps, {}>
Solution :
- We need to provide the “state” instance in second parameter
- If state interface is not defined, then create the state interface for state variables as
#state interface
export interface IKnowledgeJunctionState {
txt_projectname:string;
}
- Pass the above created “state” instance to class parameter
- So now our class looks like as
export default class KnowledgeJunction extends React.Component<IKnowledgeJunctionProps, IKnowledgeJunctionState >
- This will resolve the issue 🙂
Thanks for reading !!! Please feel free to discuss any point / share your thoughts / questions if any !!!
HAVE A GREAT TIME AHEAD 🙂