the component is not rerendering when i am using the react router rom

Viewed 33

Ok so first of all let me give routes i am using

<Header />
  <Routes>
      <Route path="/" element={<Navigate replace to="/all" />} />
      <Route path="/product" element={<ProductDetail />} />
      <Route path="/cart" element={<Cart />} />
      <Route path="/:category" element={<ProductListing products={this.state.products} />} />
  </Routes>

So i have the path category

<div className="right__bar">
          <div className='nav_link'><Link to={"/all"}>ALL</Link></div>
          <div className='nav_link'><Link to={"/clothes"}>CLOTHES</Link></div>
          <div className='nav_link'><Link to={"/tech"}>TECH</Link></div>
          <div className='nav_link'><Link to={"/cart"}>CART</Link></div>
</div>

When I am clicking the link All and then click clothes the ProductListing component does not re-render maybe because they are using the same props and the same component they have an implementation difference when I click on Clothes from the list of products it just shows the clothes category product

Below there I am pasting my ProductListing component

import React, { Component } from 'react';
// import { useParams } from 'react-router-dom';
import { Card } from '../../components'
import "./ProductListing.scss"

export class ProductListing extends Component {
  constructor(props){
    super(props);
    this.state ={
      productsToRender:{},
      loading:true,
    }
  }
  componentDidMount(){
    let {products} = this.props;
  
    const currentUrl = window.location.href;
    
    // I am checking if the all is present in the url i will set productsToRender
    // I am facing a weired issue that is  the props are not accessible to the inside if blocks
    
    
    if(currentUrl.search("all")!==-1){
      this.setState({
        productsToRender:products[0],
        loading:false,
      })
    }else if(currentUrl.search("clothes")!==-1){
      this.setState({
        productsToRender:products[1],
        loading:false,
      })
    }else if(currentUrl.search("tech")!==-1){
      this.setState({
        productsToRender:products[2],
        loading:false,
      })
    }
    
  }
  render() {
  console.log("I am executed")
    if(this.state.loading === true){
      return <h1>LOADING....</h1>
    }else{
      return (
        <div>
          <h2>{this.state.productsToRender.name}</h2>
          <div className="product__listing">
            {this.state.productsToRender.products.map((item,index)=>(
              <Card product={item}/>
            ))}
          </div>  
        </div>
      )
    }
  }
}

export default ProductListing
1 Answers

Instead of taking window.location.href you could use useParams hook, which would return your current :category

Related