1

I have the following state declaration:

constructor(props: any) {
    super(props);

    this.state = {
        orders: []
    };
}

where orders is an array of these Order structures:

interface Order {
    symbol: string,
    qty: number,
    side: Side
}

I want to map over the orders array like so:

this.state.orders.map( ( {order}, index: number) => {
    return <li key={index}>order.symbol order.qty</li>;
})

I am playing with parenthesis and curlys, cant get the syntax right, not quite sure what I am doing. My intent is "loop over the array of orders in the render method and display it"

Thank you very much

2 Answers 2

2

You don't need to destruct order in your map function. In your current syntax, map is expecting an object that has an order property for each element in the orders array.

You can simply remove the curly braces to access each order. Also, make sure you use curly braces in your JSX to differentiate between text and JS expression:

this.state.orders.map( (order: Order, index: number) => {
    return <li key={index}>{order.symbol} {order.qty}</li>;
})

See more about object destructuring.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you, this is great -- it fixes all red squiggles , but one. For "this.state" it shows [ts] ':' expected. (property) this: any
It sounds like it may need the type of each element in the map to be explicit, so something like (order: Order, index: number): JSX.Element or (order: Order, index: number): any if the former does not work
No, Christian, your suggestion does not change anything -- the addition of what you are suggesting does not seem to hurt, but the period in this.state is still red, still complaining. thank you
Never mind, there was another set of curlys around my map statement -- I thought they were a no-op, but I guess not. thank you
1

It would be :

this.state.orders.map( ( { symbol, qty }, index: number) => {
    return <li key={index}>{symbol} {qty}</li>;
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.