简体   繁体   中英

Error while passing an array to a component (React - TypeScript)

Trying to describe inputs for Component 2 but receiving an error. Please advise how to pass and describe arrays input properly.

Model:

interface IIncident {
    id: string,
    title: string
}

Component 1:

interface IncidentManagerProps {
}

interface IncidentManagerState {
    incidents: IIncident[]
}

class IncidentManager extends Component<IncidentManagerProps, IncidentManagerState> {
    constructor(props: IncidentManagerProps) {
        super(props);
        this.state = {
            incidents: []
        }
    }

    render = () => {
        const {incidents} = this.state;

        return (
            <div className={'inc-cont'}>
                <p>All Incidents</p>
                <div className={'all-inc'}>

                    //Error displayed here
                    <Incidents incidents={incidents}/>
                </div>
            </div>
        );
    }
}

Component 2: incidents any type resolve the issue but that's is not a good way

interface Incidents {
    incidents: IIncident[]
}

const Incidents = (props: Incidents) => props.incidents.map((inc: IIncident) => (
   <Incident key={inc.id} title={inc.title}/>
));

Error message:

JSX element type 'Element[]' is not a constructor function for JSX elements.
  Type 'Element[]' is missing the following properties from type 'Element': type, props, key  TS2605

render() cannot return elements array, just a single element. Try wrapping your 2nd component output to any element like this:

const Incidents = (props: {incidents: IIncident[]}) => <>
  {props.incidents.map(inc =>
    <Incident key={inc.id} title={inc.title}/>
  )}
</>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM