New to SPFx and React.
I'm trying the set the state of a TextField when I enter data into the react component and eventually use a button to drop it into a list. This is bringing information into the web part from a list using REST and that part actually works but is omitted. I was trying to create the code to set the state on the TextFields when I went down the rabbit hole on this.
The handleChange
event syntax is not right and I am unable to figure it out. Would like to be able to set the state on the MyItems.Title
to what is in the TextField so I can eventually save it.
I got this code from a course I'm taking but this part I've been unable to get to work.
export default class CrudWithReact extends React.Component<ITaWebpartProps, IMyState> {
private _selection: Selection;
private _onItemsSelectionChanged = () => {
this.setState({
MyListItem: (this._selection.getSelection()[0] as IMyListItem)
});
}
public constructor(props: ITaWebpartProps, state:IMyState) {
super(props);
this.state = {
status: "",
MyListItems: [],
MyListItem: {
Id:0,
Title: "test",
lastname:""
}
};
this.handleChange=this.handleChange.bind(this);
this._selection = new Selection({
onSelectionChanged: this._onItemsSelectionChanged,
});
}
public handleChange=(e)=>{
this.setstate({this.state.MyListItem:e.target.value});
}public render(): React.ReactElement<ITaWebpartProps>
{
const dropdownRef = React.createRef<IDropdown>();
return (
<div className={ styles.taWebpart='' }>
<TextField
label="FirstName(actually Title)"
required={ true }
readOnly={false}
defaultValue={(this.state.MyListItem.Title)}
//value={this.state.MyListItem.Title}
styles={textFieldStyles}
onChange={this.handleChange}
name="title"
/>
<TextField
label="LastName"
required={ true }
defaultValue={(this.state.MyListItem.lastname)}
/* onChange={this.handleChange} */
name='lastname'
/>
<p className={styles.title}>
<PrimaryButton
text='Add'
title='Add'
onClick={this.btnAdd_click}
/>
<PrimaryButton
text='Update'
onClick={this.btnUpdate_click}
/>
<PrimaryButton
text='Delete'
onClick={this.btnDelete_click}
/>
<PrimaryButton
text='My new button'
onClick={this.testbutton_click}
/>
</p>
<div id="divStatus">
{this.state.status}
</div>
<div>
<DetailsList
items={ this.state.MyListItems}
columns={ _mylistitemscols }
setKey='Id'
checkboxVisibility={ CheckboxVisibility.onHover}
selectionMode={ SelectionMode.single}
layoutMode={ DetailsListLayoutMode.fixedColumns }
compact={ true }
selection={this._selection}
/>
</div>
</div>
);
}
}
The Interface:
import { IMyListItem } from "./IMyListItem";
export interface IMyState {
status: string;
MyListItems: IMyListItem[];
MyListItem: IMyListItem;
}