I have the following code, which the purpose it is to be reused inside another component, and give a different link according to the id of my object, and my API return.
The problem is that, how I'm using a map function it is reproducing the same button multiple times on the screen. I want to know how I get only one button. Can I somehow use indexOf inside that map? Everything else is working just fine
const ButtonGroup = (linksReturn) => {
return linksReturn.map((urlAdress, index) => (
<div key={index}>
<button
target="_blank"
href={urlAdress["detailsUrl"]}
>
Acess Link
</button>
</div>
));
};
const PreviewActions = ({ linksReturn }) => {
return <div>{ButtonGroup(linksReturn)}</div>;
};
export default PreviewActions;
This is the part of the code where I reuse the button
import { useEffect } from 'react';
import { useParams } from 'react-router-dom';
import PreviewActions from './PreviewActions';
// ** Store & Actions
import { getInfo } from '../store/actions/index';
import { useDispatch, useSelector } from 'react-redux';
const LicitacaoPreview = () => {
const dispatch = useDispatch();
const store = useSelector((state) => state.allInfo);
const { id } = useParams();
useEffect(() => {
dispatch(getInfo(id));
}, [dispatch]);
return typeof store.lotesData === 'object' ? (
<div>
<PreviewActions
id={id}
linksReturn={store.infoData}
/>
</div>
)
};
export default LicitacaoPreview;
CodePudding user response:
Array.prototype.map()
does not work like that, it calls the function passed in as an argument on every single array elements and returns the resultant array.
A better approach would be using Array.prototype.slice()
to return specific part of the original array and then use map()
on it
const ButtonGroup = (linksReturn) => {
const newArr = linksReturn.slice(startindex, endindex); // replace with your index appropriately
return newArr.map((urlAdress, index) => (
<div key={index}>
<button
target="_blank"
href={urlAdress["detailsUrl"]}
>
Acess Link
</button>
</div>
));
};