Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React typescript pass array of name in the props

I writing the React Typescript components to take the array of Props value. but the below code giving me the error in the map statement.

Property ‘map’ does not exist on type
‘Readonly’.ts(2339)

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import * as React from 'react';

export interface IListNameProps {
    names: string[]
}

export interface IListNameState {

}

export default class ListName extends React.Component<IListNameProps, IListNameState> {

  constructor(props: IListNameProps) {

    super(props);

    this.state = {
    }
  }

  public render() {
    return (
        <ul>
          {this.props.map((name) => (
            <li key={name}>{name}</li>
          ))}
        </ul>
      );
  }
}

What is the correct way of passing array of string to React components?

Thanks

>Solution :

You need to iterate over names which you passed as props
Also I don’t see benefit of using class component its confusing, here I updated the syntax. But if you prefer to use class then just update the this.props.map to this.props.names.map

import * as React from 'react';

export interface IListNameProps {
  names: string[]
}


export default function ListNames(props: IListNameProps) {
  return (
    <ul>
    {props.names.map((name) => (
      <li key={name}>{name}</li>
    ))}
  </ul>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading