faizan_khan98
faizan_khan98

Reputation: 141

React Router: How to navigate to another component using anchor tags

I am creating a React App that displays recipes and in my Recipe component I want to be able to click on the anchor tags and navigate to another component called RecipeInfo.js and pass in some of the props along with it like {title, ingredients}. How exactly is this supposed to be set up? So far I have my Recipe component code like this

import React from "react";
export default function Recipe({ title, calories, image }) {
  return (
    <>
      <a href="/"><h1>{title}</h1></a>
      <p>{Math.round(calories)} calories</p>
      <img src={image} alt="" />
    </>
  );
}

and my App.js code like this

import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Route, NavLink } from "react-router-dom";
import Recipe from "./Recipe.js";
import RecipeInfo from "./RecipeInfo.js";
import "./styles.css";

export default function App() {
  const API_ID = "c38daf94";
  const API_KEY = "850d468a3e994692691631c7c259406c";

  const [recipes, setRecipes] = useState([]);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState();

  useEffect(() => {
    async function getRecipes() {
      const response = await fetch(
        `https://api.edamam.com/search?q=${query}&app_id=${API_ID}&app_key=${API_KEY}`
      );
      const data = await response.json();
      setRecipes(data.hits);
      console.log(data.hits);
    }
    if (query !== "") getRecipes();
  }, [query]);


  const updateRecipes = e => {
    setSearch(e.target.value);
  };

  const getSearch = e => {
    e.preventDefault();
    console.log(query)
    setQuery(search);
  };

  return (


    <div className="App">
      <input
        className="input"
        onChange={updateRecipes}
        value={search}
        type="text"
      />
      <button className="search" onClick={getSearch}>
        Search
      </button>
      <div className="recipes">
        {recipes.map(recipe => (
          <Recipe
            key={recipe.recipe.uri}
            title={recipe.recipe.label}
            calories={recipe.recipe.calories}
            image={recipe.recipe.image}
          />
        ))}
      </div>
      <Router>
        <Route
        exact path = "/recipeinfo"
        render={props => (
          <RecipeInfo
          {...props}

          />
        )}
        />
      </Router>
    </div>
  );
}

Upvotes: 1

Views: 5416

Answers (3)

Andreas
Andreas

Reputation: 444

Replacing a tag with Link component should work. I noticed some more issues in the code:

  • there was a key provided in Recipe component, however the component itself was making no use of it, so it was pointless. Replaced fragment with div and provided the key there

  • Trying to render the object {ingredients} as is would not work, since objects cannot be rendered by react. Replaced with a map, rendering ingredient.text

  • Added the render method to Route exact path="/recipeinfo" like this, to acess ingredients inside the RecipeInfo component:

    <Route exact path="/recipeinfo" render={() => (<RecipeInfo title={title} ingredients={ingredients}/>)}/>

Here is a working example

Upvotes: 0

Muhammad Usama Rabani
Muhammad Usama Rabani

Reputation: 776

import {Link} from 'react-router-dom';

and then replace <a> with <Link to='/'>

Upvotes: 4

adz5A
adz5A

Reputation: 2032

In your first snippet you change your a tag with a Link component exported by react-router.

You can look at this example from the docs for an example of custom Link integration. This component is useful because it will make call to the history API instead of just trying to load the url into the page.

Upvotes: 2

Related Questions