skip to Main Content

I am trying to navigate different cards to their respective pages using react-router and use-Navigate but can’t ,as the onclick functionality is not working.

    import React from 'react';
import { Link  , useNavigate} from 'react-router-dom';

const Card = ({ id, imageSrc, title, text }) => (
  <Link to={`/card/${id}`} className="card-link">
    <div className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition duration-300">
      <img src={imageSrc} alt="Card" className="w-full h-auto" />
      <div className="p-4">
        <h3 className="text-xl font-semibold mb-2">{title}</h3>
        <p className="text-gray-700">{text}</p>
      </div>
    </div>
  </Link>
);

const Action = () => {
  const cardsData = [
    { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: 'The story follows Ken Kaneki, a student who barely survives a deadly encounter with Rize Kamishiro,his date who reveals herself as a ghoul and tries to eat him. He is taken to the hospital in critical condition. ' },
    { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: 'High school student Yuuichi Katagiri cherishes his close circle of friends, composed of four classmates: Yutori Kokorogi,Shiho Sawaragi, Makoto Shibe, and Tenji Mikasa. However, when the funds for the upcoming school trip are stolen, the incident causes Shiho and Makoto—who had been tasked with collecting the money—to distance ' },
    { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "Ever since the death of his father, the burden of supporting the family has fallen upon Tanjirou Kamado's shoulders.Though living impoverished on a remote mountain, the Kamado family are able to enjoy a relatively peaceful and happy life.One day, Tanjirou decides to go down to the local village to make a" },
    { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "A fleet of pirate ships with the same Jolly Roger are shown along with a man sporting said flag, Woonan.Next a night scene where piles of gold treasure are seen bright at sea with a silhouette of Woonan.  Then an island is shown while gold rains down as it fades out ending with a shot of a treasure map." },
    { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: 'Admired at school for her friendly attitude and academic achievements, high school student Kyouko Hori has been hiding another side of herself.With her parents often away from home due to work, Hori also has to look after her younger brother and do the housework, leaving no opportunities .' },
    { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "Even in his past life, Cid's dream wasn't to become a protagonist or a final boss.He'd rather lie low as a minor character until it's prime time to reveal he's a mastermind...or at least, do the next best thing-pretend to be one! And now that he's been reborn into another world, he's ready to set the perfect conditions  to live out his dreams to the fullest." },
    // Add more card data as needed
  ];

  const navigate = useNavigate();

  const navigateToCardDetails = (id) => {
    // Navigate to the card details page based on the ID
    switch (id) {
      case 1:
        navigate(`/card/${id}`);
        break;
      // cases for other IDs...
      default:
        break;
    }
  };

  return (
    <div className="grid grid-cols-1 mt-[616px] sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
      {cardsData.map(card => (
        <div key={card.id} onClick={() => navigateToCardDetails(card.id)}>
          <Card id={card.id} imageSrc={card.imageSrc} title={card.title} text={card.text} />
        </div>
      ))}
    </div>
  );
};

export default Action;

In the Action component, I’m trying to navigate to different pages when clicking on each card using React Router’s use-Navigate hook. However, the navigation doesn’t seem to work as expected.

2

Answers


  1. Chosen as BEST ANSWER
    import React from 'react';
    import { Link } from 'react-router-dom';
    
    const Card = ({ id, imageSrc, title, text }) => (
      <Link to={`/card/${id}`} className="card-link">
        <div className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition duration-300">
          <img src={imageSrc} alt="Card" className="w-full h-auto" />
          <div className="p-4">
            <h3 className="text-xl font-semibold mb-2">{title}</h3>
            <p className="text-gray-700">{text}</p>
          </div>
        </div>
      </Link>
    );
    
    const Action = () => {
      const cardsData = [
        { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: 'The story follows Ken Kaneki, a student who barely survives a deadly encounter with Rize Kamishiro,his date who reveals herself as a ghoul and tries to eat him. He is taken to the hospital in critical condition. ' },
        { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: 'High school student Yuuichi Katagiri cherishes his close circle of friends, composed of four classmates: Yutori Kokorogi,Shiho Sawaragi, Makoto Shibe, and Tenji Mikasa. However, when the funds for the upcoming school trip are stolen, the incident causes Shiho and Makoto—who had been tasked with collecting the money—to distance ' },
        { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "Ever since the death of his father, the burden of supporting the family has fallen upon Tanjirou Kamado's shoulders.Though living impoverished on a remote mountain, the Kamado family are able to enjoy a relatively peaceful and happy life.One day, Tanjirou decides to go down to the local village to make a" },
        { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "A fleet of pirate ships with the same Jolly Roger are shown along with a man sporting said flag, Woonan.Next a night scene where piles of gold treasure are seen bright at sea with a silhouette of Woonan.  Then an island is shown while gold rains down as it fades out ending with a shot of a treasure map." },
        { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: 'Admired at school for her friendly attitude and academic achievements, high school student Kyouko Hori has been hiding another side of herself.With her parents often away from home due to work, Hori also has to look after her younger brother and do the housework, leaving no opportunities .' },
        { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "Even in his past life, Cid's dream wasn't to become a protagonist or a final boss.He'd rather lie low as a minor character until it's prime time to reveal he's a mastermind...or at least, do the next best thing-pretend to be one! And now that he's been reborn into another world, he's ready to set the perfect conditions  to live out his dreams to the fullest." },
        // Add more card data as needed
      ];
    
     
    
      return (
        <div className="grid grid-cols-1 mt-[616px] sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
          {cardsData.map(card => (
          
              <Card key={card.id} id={card.id} imageSrc={card.imageSrc} title={card.title} text={card.text} />
         
          ))}
        </div>
      );
    };
    
    export default Action;
    
    ```This is my Cards content page code```
    
    
    
    
    
    
    import './index.css'
    import Navbar from "./components/Navbar/navbar.js";
    import Sliding from './components/Sliding/sliding.js';
    import Action from './components/collections/Action.js';
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    import CardDetails from './components/CardDetails.js';
    
    function App() {
      return (
        <Router> {/* Move the top-level Router here */}
          <div className="relative">
            <Navbar />
            <Sliding />
            
            <Routes>
            <Route path="/" element={<Action />} />
            <Route path="card/:id" element={<CardDetails />} />
            
          </Routes>
          </div>
        </Router>
      );
    }
    
    export default App;
    

    This is my App.js Code

    import { useParams } from 'react-router-dom';
    import tokyo_ghoul from './collections/tokyo_ghoul';
    
    const lookup = {
      1: tokyo_ghoul,
      // Add more mappings as needed
    };
    
    const CardDetails = () => {
      const { id } = useParams();
      const Details = lookup[id];
    
      return Details ? <Details /> : <div>No data found for id: {id}</div>;
    };
    
    export default CardDetails;
    

    this is CardDetails code

    But when i click on the card1 it still not navigating to tokyo_ghoul page


  2. You are trying to navigate to paths like "/card/1" and "/card/2", but render a route like "/card1", so path "/card/1" has no matching route.

    Update the routing configuration to specify route paths that match the link paths you are targeting.

    Example:

    <Router>
      <div className="relative">
        <Navbar />
        <Sliding />
        <Routes>
          <Route path="/" element={<Action />} />
          <Route path="card/1" element={<TokyoGhoul />} />
          <Route path="card/2" element={<Tomodachi />} />
          {/* etc */}
        </Routes>
      </div>
    </Router>
    

    or

    <Router>
      <div className="relative">
        <Navbar />
        <Sliding />
        <Routes>
          <Route path="/" element={<Action />} />
          <Route path="card">
            <Route path="1" element={<TokyoGhoul />} />
            <Route path="2" element={<Tomodachi />} />
            {/* etc */}
          </Route>
        </Routes>
      </div>
    </Router>
    

    The Link component rendered in Card should be sufficient enough to trigger a navigation action to the specific route.

    const cardsData = [
      { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: '....' },
      { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: '....' },
      { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "...." },
      { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "...." },
      { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: '....' },
      { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "...." },
      // Add more card data as needed
    ];
    
    const Action = () => {
      return (
        <div className="....">
          {cardsData.map(card => (
            <Card
              key={card.id}
              id={card.id}
              imageSrc={card.imageSrc}
              title={card.title}
              text={card.text}
            />
          ))}
        </div>
      );
    };
    

    To avoid repetitive route code/logic like this it’s a common practice to define a single route path with a dynamic path segment to match id values.

    Example:

    <Router>
      <div className="relative">
        <Navbar />
        <Sliding />
        <Routes>
          <Route path="/" element={<Action />} />
          <Route path="card/:id" element={<CardDetails />} />
          {/* other routes */}
        </Routes>
      </div>
    </Router>
    

    This new CardDetails component would read the id value from the route path parameters and compute the correct UI to render.

    import { useParams } from 'react-router-dom';
    import {
      TokyoGhoul,
      Tomodachi,
      ....
    } from '../components';
    
    const lookup = {
      1: TokyoGhoul,
      2: Tomodachi,
      ... etc ...
    };
    
    const CardDetails = () => {
      const { id } = useParams();
    
      const Details = lookup[id];
    
      return Details ? <Details /> : <div>No data found</div>;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search