1

I am trying to map through an array and return jsx however I'm using Typescript and so .map only returns functions (not jsx). How can I loop through the array and return some jsx for each array element in React?

I already have return (<div>{array.map(this.function)}</div>) so I'm returning a function on each array element but I would like to return both jsx and a function from map. I've tried this {array.map(() => {return this.function && <p>text</p>})} but it's just returning either the jsx or the function.

What I want to achieve: When I map through the array, I want to run a function on each array element as well as return a paragraph <p></p> on each element so that I can display some text next to the output of the function.

Any help would be appreciated!

5
  • 1
    map returns whatever the callback function returns, so if the map returns a function, then you are calling it wrong, perhaps try calling the callback twice? array.map((...args) => this.function(...args)()) Commented Dec 15, 2020 at 10:45
  • Can you clarify what you mean by I would like to display some jsx next to the rendered function Commented Dec 15, 2020 at 10:50
  • Can you show the return of this.function? It is also important to make sure you are using HOC correctly to get a function using this. Commented Dec 15, 2020 at 10:55
  • Ah yes I see thanks, I returned some jsx but I need to return jsx and a function. Is it possible to return both jsx and a function from .map? I tried using && but it's returning either the jsx or the function? @KrzysztofKrzeszewski Commented Dec 15, 2020 at 10:57
  • i feel like this may be a case of an XY problem can you provide us with more details on what you are trying to achieve, instead of how you tried to achieve it? Commented Dec 15, 2020 at 11:10

1 Answer 1

2

Don't forget to add the proper key:

{array.map((el) => (
    <React.Fragment key={}>
        {this.function(el)}
        <p>text</p>
    </React.Fragment>
 ))}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thank you! The problem was that I wasn't actually calling the function, I added () and it worked. @HaJa

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.