1
votes

I'm trying to push an item into a array stored in the properties, I'm getting an error: Cannot read properties of undefined (reading 'value')

in the props I have:

ILinkItemProps.ts

export interface ILinkItemProps {
  id:string;
  title:string;
  action:string;
  anchorid:string;
  trans:string;
}

export class LinksItem implements ILinkItemProps {
    constructor (
        public id: string  = null, 
        public title: string = null, 
        public action: string = null,
        public anchorid: string = null,
        public trans: string = null) { }
}

ILinksProp.ts

import {LinksItem} from './ILinkItemProps';
export interface ILinksProps {
    linkItems:Array<LinksItem>;
}

in the webpart.ts I have:-

public render(): void {
    const element: React.ReactElement<ILinksProps> = React.createElement(
      links,
      {
 linkItems: this.properties.linkItems,
 updateEditLink: (index: number) => {
            let arr = this.properties.linkItems;
            if (arr?.push) {
              arr.push(new LinksItem());
            } else {
              console.log('arr is undefined or null');
            }
        }

    }
)

has anyone got any ideas why the Array is undefined?

1

1 Answers

0
votes

Using this.props rather than this.properties should give you access to props passed to the component. Here is your example rewritten to use this.props:

import React from 'react';

export interface ILinkItemProps {
  id:string|null;
  title:string|null;
  action:string|null;
  anchorid:string|null;
  trans:string|null;
}

export class LinksItem implements ILinkItemProps {
    constructor (
      public id: string|null  = null, 
      public title: string|null = null, 
      public action: string|null = null,
      public anchorid: string|null = null,
      public trans: string|null = null) { }
}

export interface ILinksProps {
  linkItems:Array<ILinkItemProps>;
}

export class MyList extends React.Component<ILinksProps> {
  render() {
    return <div>List count: {this.props.linkItems.length}</div>;
  }
}

export default class App extends React.Component {
  render() {
    return <MyList linkItems={[
      {id: '1'} as ILinkItemProps
    ]} />
  }
}