satyajit
satyajit

Reputation: 694

how to render to a page whenever user click to a dynamic url ReactJS?

what i am trying to solve is, how to render to a specific page whenever user click to dynamic url? for more specific, there is my "product_list" api data. in "product_list" api data there is a key "url", whenever user click on this "url" then user will be redirect to another specific "product_detail" page. how to implement that specific dynamic url page to a specific page? so whenever user will click the url then user will see a specific UI page, not that dynamic url page.

i am probably new to reactjs. i am trying to solve this problem but i have no idea where i am doing thing wrong. it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance.

// product_list api-data -->

[
    {
        "url": "http://localhost:8000/api/p/product01",
        "id": 19,
        "title": "product01",
        "slug": "product01",
        "description": "product01descc",
        "image": "http://localhost:8000/media/google.com/images/tet0.png",
        "price": 1,
        "status": true,
        "created_on": "2020-04-19T03:45:12Z"
    },
    {
        "url": "http://localhost:8000/api/p/product02",
        "id": 20,
        "title": "product02",
        "slug": "product02",
        "description": "product01descc",
        "image": "http://localhost:8000/media/google.com/images/tet0.png",
        "price": 2,
        "status": true,
        "created_on": "2020-04-19T03:45:12Z"
    }
]


product detail api-data of specific product list, for e.g "product-01".

{
    "id": 19,
    "title": "product01",
    "slug": "product01",
    "description": "product01descc",
    "image": "http://localhost:8000/media/google.com/images/tet0.png",
    "price": 1,
    "created_on": "2020-04-19T03:45:12Z",
    "status": true,
    "color": 1,
    "size": 1,
    "product_category": []
}


my efforts to trying to solve this problem.

./src/productList.js


import React, {Component} from "react";
import Contacts from './productListHook.js';


export default class App  extends Component{

    state = {
        contacts: [

        ]
    }

    contactList() {
        fetch('http://localhost:8000/api/p_list')
        .then(res => res.json())
        .then((data) => {
          this.setState({ contacts: data })
        })
        .catch(console.log)
      }

    render(){
    return(

        <Contacts contacts={this.state.contacts} />
    )
 }
}


in this page, whenever i am trying to rendering user, when user click to the "title" as you can see below. but that page rendering user to the api-detail page. obviously that would be cause i did not implement to that api-detail page to a specific page where user will see the UI detail page. how to do implement that in reactjs?

./src/productListHook.js


import React from 'react'

    const Contacts = ({ contacts }) => {
      return (
            {contacts.map((contact) => (
            <img src={contact.image} alt="" class="img-fluid" />
            <h3> <a href={contact.url}>{contact.title}</a> </h3>

            ))}
      )
    };

export default Contacts

Upvotes: 0

Views: 748

Answers (2)

Ajin Kabeer
Ajin Kabeer

Reputation: 2186

Another way to approach this would be to add a <Link /> component in the map function of contacts and pass down the details as props. Also, you have to set up the Router component to render the page. Assuming <App /> as your root component, you have to wrap this component with BrowserRouter inside your index.js file. Here's a working sandbox.

//Contacts.js
import React from "react";
import { Link } from "react-router-dom";

const Contacts = ({ contacts }) => {
  return (
    <div>
      {contacts.map((contact) => (
        <div key={contact.id>>
          <img src={contact.image} alt="" className="img-fluid" />
          <h3>
            {" "}
            <Link
              to={{
                pathname: `/productdetails/${contact.id}`,
                contact: contact,
              }}
            >
              {contact.title}
            </Link>
          </h3>
        </div>
      ))}
    </div>
  );
};

export default Contacts;
//App.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./Home";
import ProductDetails from "./ProductDetails";

function App() {
  return (
    <div className="App">
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/productdetails/:slug" component={ProductDetails} />
      </Switch>
    </div>
  );
}

export default App;

The Home component in the App.js would be the App.js in your question.

//ProductDetails.js
import React from "react";
import {  useLocation } from "react-router-dom";

function ProductDetails({ location }) {
  const { contact } = location;
  console.log(contact);
  let queryParams= useLocation();
  console.log(queryParams)
  return (
    <div>
      <h1>Product Details Page</h1>;
    </div>
  );
}

export default ProductDetails;

In the ProductDetails component, you can access queryParams and the props passed down from Contacts component with which you can make additional API requests to render data.

Upvotes: 1

Sandy
Sandy

Reputation: 11687

For dynamic URLs, you may not want to go with absolute paths. Consider shifting to query parameters.

Change url to http://localhost:8000/api/p?id=product01. In routing, render ProductDetailContainer for url 'http://localhost:8000/api/p'.

function ProductDetailContainer() {
    const query = new URLSearchParams(useLocation().search); // useLocation in react-router

    return <ProductDetail id={query.get('id')} />;
}

function ProductDetail({id}) {
    return ({id}); // Render details based on the ID fetched.
}

Code above is not tested. Please adapt accordingly :)

Hope it helps.

Upvotes: 0

Related Questions