Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – Imported array of objects not reversing

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading