Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Cannot route to required React Component using React-Router-DOM

I am trying to route to the component "Products" from my Homepage as per the product id from the item list from the Home Component. My page is getting routed to 'localhost:3000/id' but it is not getting the Products component. There are no errors that I faced. I fetched the data from the fake API and displayed the products on the home page. After clicking the product I want the page to route to "Product" component. The address is routing as expected but the component is not loading.

import React, { Component } from "react";
  import {
   BrowserRouter as Router,
   Switch,
   Route,
   Link
    } from "react-router-dom";

   import Products from "./Products";

   interface Props {}

   interface ResponseData {
    id: number;
    price: number;
    description: string;
    image: string;
   }

   interface State {
    response: ResponseData[];
   }

export default class Home extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      response: [],
    };
  }
  getProductsData = async () => {
    const apiResponse = await    fetch("https://fakestoreapi.com/products");
    console.log(apiResponse);
    const responseData = await apiResponse.json();
    this.setState({
      response: responseData,
      });
     };

  componentDidMount() {
     this.getProductsData();
   }
   render() {
     const { response } = this.state;
     if (response.length === 0) {
       return <div className="loader">Loading the items.......     </div>;
    }
     return (
       <div >
         <div className="product-list">
           {response.map((resp) => (
              <Switch>
              <Link className = "product-cards" 
              to={`${resp.id}`} >
              <Route path={`${resp.id}`} component={Products}/>
               <div className="product-cards">
               <img src={resp.image} />
               <div className="product-description">{resp.description}</div>
                <div className="product-price">{resp.price}</div>
            </div>
            </Link>
           </Switch>
         ))}
       </div>
     </div>
    );
   }
 }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You probably need to replace your switch routes to App component and in this Home component just use a Link to redirect to the path you want.

function App() {
  return (
    <Switch>
      <Route exact path="/" component={ Home } />
      <Route path="/:id" component={ Products } />
    </Switch>
  );
}

Home component return should be something like this:

return (
  <div className="product-list">
    {response.map((resp) => (
      <Link
        className = "product-cards" 
        to={`/${resp.id}`}
      >
        <div className="product-cards">
          <img src={resp.image} />
          <div className="product-description">{resp.description}</div>
          <div className="product-price">{resp.price}</div>
        </div>
      </Link>
    ))}
  </div>
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda