Carlos Escobar
Carlos Escobar

Reputation: 434

cant access the state in a functional component with useLocation from react-router-dom

I'm trying to access a state property I'm passing through NavLink into a component but I can't get it to work. I read that it was as simple as using useLocation to access the state, but I think typescript does not like this.

below code:

import React from "react";
import "./project.css";
import Toolbar from "../navigation/toolbar";
import Footer from "../footer/footer";
import projects from "../projectsSection/projects";
import { useLocation } from "react-router-dom";

interface ProjectProps {
  projectId: number;
}
const Project: React.FC = (props) => {
  const { state } = useLocation();
  const { projectId } = state;

  const project = projects.find((project) => project.id === projectId);

  return (
    <section className="project-main">
      <Toolbar />
      <div></div>
      <Footer />
    </section>
  );
};

export default Project;

Any idea how can I access state in similar setup? I get an error that says: Property 'projectId' does not exist on type 'unknown

Upvotes: 1

Views: 1288

Answers (1)

DavidGregorian
DavidGregorian

Reputation: 81

You need to add a generic type to useLocation:

const { state } = useLocation<{projectId: string}>();

Upvotes: 3

Related Questions