N
N
nivaech2019-02-04 15:17:29
JavaScript
nivaech, 2019-02-04 15:17:29

How to change the url of a component when its state changes?

There is a page-component of an online store, which, by clicking on certain menu items, displays certain categories of products. There is only one component for displaying different categories, that is, it has one url in react-router. How to make it so that when the state of this component changes, the displayed url also changes?
I did so. Specified url value in state:

state = {
    productType1: false,
    productType2: false,
    link: ' '
  }

Next are the functions that change the state of the component on click, and here the url is changed so that it changes in accordance with the displayed category:
showProductType1= () => {
    this.setState(() => {
      return {
        productType1: true,
        productType2: false,
        link: '/product_type1',
      }
    })
  }

  showProductType2= () => {
    this.setState(() => {
      return {
        productType2: true,
        productType1: false,
        link: '/product_type2',
      }
    })
  }

Further, all this information is passed to the component responsible for displaying different categories of products.
<Route exact path={this.state.link} render={(props) => 
<ProductList {...props} productType1={this.state.productType1} productType2={this.state.productType2} />}></Route>

And the functions are passed to the navbar component so that by clicking on the category the state of the main component changes.
<Navbar 
showProductType1 = {this.showProductType1} 
showProductType2 = {this.showProductType2} 
link={this.state.link}/>

In general, such a condition works half. When clicking on different categories of products, the url of the component does change, but only if you click on the menu item twice. After the first click, nothing happens, the component is not updated, hence no change. After the second click, both the component and the displayed link are already updated, and everything is rendered correctly.
How to correctly change the component url depending on the state change?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question