I have a React functional component with the following JSX:
import React from "react";
const Parent = () => {
const arr1 = ["123", "456"];
const arr2 = ["abc", "def"];
return (
<div>
{arr1.map((item) => {
return <div>{item}</div>;
})}
{arr2.map((item) => {
return <div>{item}</div>;
})}
</div>
);
};
export default Parent;
What I need this component to render is:
"123"
"abc"
"456"
"def"
Instead, it returns:
"123"
"456"
"abc"
"def"
I tried to get the result with a for loop, but for some reason it doesn't get triggered when the functional component is loaded, so I'm looking for a solution that involves .map(). Is there a way to get the needed result with .map()?
Note: the lengths of arrays are always equal, hence the accepted answer.
Assuming that both array have the same length:
<div>
{arr1.map((item, index) => (<>
<div>{item}</div>
<div>{arr2[index]}</div>
</>);
)}
</div>
return (
<div>
{arr1.map((value, index) => {
return <> <div>{value}</div> <div>{arr2[index]}</div> </>
})}
</div>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With