Home > Back-end >  How to pass props via Link in React (this.props.location is undefined)
How to pass props via Link in React (this.props.location is undefined)

Time:12-29

i am creating a recipe research project in react. On the home page I press 'search recipe' and it finds them for me, then 'view recipe' and it should show me some data that I have to decide. When in the component I go to do the console.log (this.props) it returns me all the object without the value of the state and therefore I cannot access the data. could you please help me? I leave you the code to understand better.

import logo from "./logo.svg";
import "./App.css";
import React, { useState } from "react";
import MealList from "./MealList";

function App() {
  const [mealData, setMealData] = useState(null);
  /*const [calories, setCalories] = useState(2000)*/
  const [food, setFood] = useState("");

  function handleChange(e) {
    setFood(e.target.value);
  }

  function getMealData() {
    fetch(
      `https://api.spoonacular.com/recipes/complexSearch?apiKey=1d66c25bc4bb4ac288efecc0f2c4c4b8&diet=vegetarian` 
    ) /* &addRecipeInformation=true */
      .then((response) => response.json())
      .then((data) => {
        setMealData(data);
      })
      .catch(() => {
        console.log("error");
      });
  }

  return (
    <div className="App">
      <section className="controls">
        {/*<input type="number" placeholder='Calories (e.g. 2000)' onChange={handleChange}/>*/}
        <input type="string" placeholder="food" onChange={handleChange} />
      </section>
      <button onClick={getMealData}> CERCA PASTI VEGETARIANI</button>
      {mealData && <MealList mealData={mealData}/>}
    </div>
  );
}

export default App;


import React from "react";
import Meal from "./Meal";

export default function MealList({ mealData }) {

  return (
<main>
  <section className="meals">
    {mealData.results.map((meal) => {
      return <Meal key={meal.id} meal={meal} />;
    })}
  </section>
</main>

); }

import React, {useState, useEffect} from 'react'
import {Link} from 'react-router-dom'

export default function Meal({meal}) {
    
    const [imageUrl, setImageUrl] = useState("");
    useEffect(()=>{
        fetch(`https://api.spoonacular.com/recipes/${meal.id}/information?apiKey=1d66c25bc4bb4ac288efecc0f2c4c4b8`)
        .then((response)=>response.json())
        .then((data)=>{
            setImageUrl(data.image)
        })
        .catch(()=>{
            console.log("errorn in meal js fetch")
        })
    }, [meal.id])

    const location = {
        pathname: '/somewhere',
        state: { fromDashboard: true }
      }
    return (
        <article>
            <h1>{meal.title}</h1>
            <img src={imageUrl } alt="recipe"></img>
            <div>
                <button className='recipeButtons'>
                    <Link to={{
                        pathname: `/recipe/${meal.id}`, 
                        state: {meal: meal.id}}}>
                        Guarda Ricetta
                    </Link>
                </button>
            </div>
        </article>
    )
}



import React from "react";

class Recipe extends React.Component{
   
    render() {
        console.log(this.props)
        return(
            <div>class Recipe extends React.Component</div>
        )
    }
}


export default Recipe;

this is the result of console.log(this.props) (this.props.location is undefined): this props

CodePudding user response:

you can use functional component with react router hooks to access to the location instead of class component


import { useLocation } from "react-router-dom";

export default function Recipe () {
const location  = useLocation();

 return (
  <div> Recipe </div
 )
}

CodePudding user response:

You haven't shown how you render <Recipe />, so I can't tell at a glance where the problem is.

However, you don't need to pass location as a prop. React-Router includes a hook, useLocation, which can be invoked from any function component. You can change Recipe to a function component and use:

import { useLocation } from 'react-router-dom'

/* ... */

function Recipe(props) {
  const location = useLocation()
  /* ... */
}

ETA:

Checking the type definitions for <Link/> and To, it appears the API reference on reactrouter.com is wrong. To is, in fact, string | Partial<Path>, where Path is:

interface Path {
    /**
     * A URL pathname, beginning with a /.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname
     */
    pathname: Pathname;
    /**
     * A URL search string, beginning with a ?.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search
     */
    search: Search;
    /**
     * A URL fragment identifier, beginning with a #.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash
     */
    hash: Hash;
}

This is why the state is never being set. To set the state in the link, you need to include it as a React prop, like so:

<Link to={`/recipe/${meal.id}`} state={{ meal: meal.id }}>Guarda Ricetta</Link>
  • Related