I’m trying to reverse an array of objects that I import from a js file. Right now it only works when I put the array straight in my component where I want to display that data, not when I import it from another file. I can’t figure out what the issue is, please let me know if I need to provide some additional information!
I have data constructed like this in a js file:
const projects = [
{
id: 1,
title: "React Tv-show App",
url: "url",
image: "image",
},
{
id: 2,
title: "React Landing Page",
url: "url",
image: "image",
},
etc..]
export default projects;
My component where I want to display and reverse that data looks like this:
import data from "./projects";
export default function ProjectsView() {
const projects = data.reverse();
return (
<div className="projectsView">
<h1 className="projectsTitle">Projects</h1>
<div className="projectsRow">
{projects.map((project) => {
return (
<Project
key={project.id}
title={project.title}
url={project.url}
image={project.image}
/>
);
})}
</div>
</div>
);
}
I also tried projects.reverse().map() in the render but that didn’t work either.
>Solution :
array.reverse() reverses an array in-place, so your array is being reversed on every render.
Use const projects = [...data].reverse(); instead. This will create a new array instead of mutating your existing array.