'Accessing data from local file by id (from params, React Router v6)

I have a file project.js which includes data stores in const projects = [{id:1, name: lala, etc.}]. I can easily access the data via array.map function, but I cannot figure out how to only access one object from the array using id sourced from the params (React Router v6 - useParams()).

I tried to fetch and I tried different combinations with ${id} in both path and fetch etc.

Project.js

import styled from "styled-components";
import projects from "../assets/data/projects";
import { useParams } from "react-router-dom";

const ProjectStyles = styled.main``;
const Project = () => {
  const { id } = useParams();

  return <ProjectStyles>DATA SHOULD BE HERE and show only one object based on id</ProjectStyles>;
};

export default Project;

Projects.js

import {
  FaReact,
  FaHtml5,
  FaCss3Alt,
  FaJsSquare,
  FaGulp,
  FaSass,
} from "react-icons/fa";
import { SiStyledcomponents, SiReactrouter, SiGatsby } from "react-icons/si";
import { GiWomanElfFace } from "react-icons/gi";
import CPHNightClub from "../img/CPHNightClub.png";
import LandrupDans from "../img/LandrupDans.png";
import SmartLights from "../img/SmartLights.png";
import TheProudTracker from "../img/TheProudTracker.png";
import iPlayMusic from "../img/iPlayMusic.png";
import NewsBox from "../img/NewsBox.png";
import Portfolio from "../img/PHolm.png";
import GatsbyAndStyle from "../img/GatsbyAndStyle.png";
const projects = [
  {
    id: 1,
    name: "CPH Night Club",
    head: "Final Exam - simple website with focus on animations",
    desc: "Final Exam at school, a simple website for a night club with lots of animations. Users can see many relevant details regarding the clubs offer, see the gallery, testimonials as well as the newest blogposts and collaborate on that with other users. Besides, the contact info (and contact formular) are provided. Not deployed at it was only working locally with school-provided API.",
    stack: [<FaReact />, <SiStyledcomponents />, <SiReactrouter />],
    link: "not deployed",
    github: "#",
    date: "March 2022",
    img: CPHNightClub,
  },
  {
    id: 2,
    name: "Landrup Dans",
    head: "(Pre-final) Exam, an app for a dance school",
    desc: "Pre-exam (final), an app for a dance school (school project). The app is supposed to give users and teachers overview at activities at school and all important details. It gives possibility to sign for activities. Not deployed at it was only working locally with school-provided API.",
    stack: [<FaReact />, <SiStyledcomponents />, <SiReactrouter />],
    link: "not deployed",
    github: "#",
    date: "March 2022",
    img: LandrupDans,
  },
  {
    id: 3,
    name: "Smart Lights (Hue)",
    head: "Smartlights App based on Philips Hue API (school project)",
    desc: "This app is a school project - where focus was on object oriented programming. Its purpose was to communicate with the physical lamps provided by school (Philips Hue bulbs) via the bridge and Philips Hue API for developers. Not deployed as it is only working on the local bridge and its API.",
    stack: [<FaReact />, <GiWomanElfFace />, <SiReactrouter />],
    link: "not deployed",
    github: "https://github.com/paulineholm/smartlights-hue",
    date: "February 2022",
    img: SmartLights,
  }
];

export default projects;


Solution 1:[1]

You could filter projects using Array.prototype.filter() method

Project.js
import styled from "styled-components";
import projects from "../assets/data/projects";
import { useParams } from "react-router-dom";

const ProjectStyles = styled.main``;
const Project = () => {
  const { id } = useParams();
  const filteredProject = projects.filter(thisProject => thisProject.id === id);
 // use filteredProject 
  return <ProjectStyles>DATA SHOULD BE HERE and show only one object based on id</ProjectStyles>;
};

export default Project;

Solution 2:[2]

projects is an array, use the Array.prototype.find method to search the array for an element with matching id.

Things to keep in mind:

  • The id route param will be a string type while the id property in your projects data is a number type, so you'll need to use a type safe comparison when searching the array when using strict equality (i.e. ===).
  • Array.prototype.find returns undefined if no matching element is found with the predicate function. The UI code should gracefully handle missing/not found project data.

Code

const Project = () => {
  const { id } = useParams();
  const project = projects.find(project => String(project.id) === id);

  return project
    ? (
      <ProjectStyles>
        ... render project data as JSX ...
      </ProjectStyles>
    )
    : "No project found.";
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deepak kumar jain
Solution 2 Drew Reese