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

294
Visualizações
Dynamically create pages based on slug from API in ReactJS

I have been learning about React Router have run into some issues while I was trying to implement a dynamic page creation based on the slugs that I receive from my fetch api call.

basically, I'm trying to redirect user to a new page after they click on a link - This new page will be a new component and I will make a new api call on this component with the slug as my search parameter.

However I'm struggling to dynamically change pages based on slugs.

Here is the component (BoxScore.js) in which I make the initial fetch and display data -

import React from "react";
import { useEffect, useState } from "react";

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

const BoxScore = () => {
  const [users, setUsers] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);



  useEffect(() => {
    fetch(
      `myfetchapihere.com`
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setUsers(data);
        console.log(data);
        setPageNumber(pageNumber);
      });
  }, [pageNumber]);
     return (
         <> {users.map((user) => (
                <div
                  className="column"
                  key={user.id}
                  id={user.id}>
                  <div className="inner">
                    <div className="flex">
                      <h2 className="uk-text-small">
                     
         

 <Link to={user.slug} className="h2 link" id={user.slug}>
    {user.name}
    </Link>
    </div>

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

In my App.js I have react router set up -

 <Routes>
      <Route path="boxscore/:slug" element={<BoxScore />}>
      <Route path=":slug" element={<OneScore />} />
    </Route>

   </Routes>

My OneScore component which isn't being rendered on the click of the link I set up in the Boxscore component -

import React from 'react'
import BoxScore from './Boxscore'
import { useParams } from "react-router";
import {useEffect} from 'react'

function OneScore() {

    const { slug } = useParams();
    
  useEffect(() => {
    // Fetch post using the postSlug
    console.log({slug});
  }, [slug]);

  return (
    <div>
          Hiii
    </div>
  )
}

export default OneScore

EDIT - I have managed to make the linking work thanks to @DrewReese comments however, the only issue remains now is that after the url is changed to (ex- www.a.com/boxscore/) the 'OneScore' component is not rendered instead the same BoxScore remains just the url is changed.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of a raw anchor (<a />) tag use the Link or NavLink component. These link components work with the routing context being provided by the router. Using the anchor tag will reload the app, which very likely isn't what you want to occur.

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

...

{users.map((user) => (
  <div
    className="column"
    key={user.id}
    id={user.id}
  >
    <div className="inner">
      <div className="flex">
        <Link to={user.slug} className="h2link" id={user.slug}>
          <h2 className="uk-text-small">{user.name}</h2>
        </Link>
      </div>
    </div>
  </div>
)};

The routed component should use the useParams hook to access the route's slug path param and an useEffect hook to rerun any logic that depends on this slug value.

import { useEffect } from 'react';
import { useParams } from 'react-router-dom';

...

const { slug } = useParams();

useEffect(() => {
  // "make a new api call on this component with the slug as my search parameter"
}, [slug]);
about 4 years ago · Juan Pablo Isaza Relatório

0

Look into useParams to get the slug from the url. https://v5.reactrouter.com/web/api/Hooks/useparams

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