Link changes url, but does not rerender the component


#1

Hey guys, my first post here. I’m building a small asignment with React + Meteor and i run into a problem: tags change the url, but the components dont change. Only after i refresh the webapp the component changes. I want to have a sidebar all of the time and render the other component depending on the URL WITHOUT REFRESHING THE PAGE.

here are the components:

import React from ‘react’;
import Sidebar from ‘./Sidebar’;
import { BrowserRouter, Switch, Route } from ‘react-router-dom’;
import CustomersComponent from ‘./panel-parts/Customers’;
import OrdersComponent from ‘./panel-parts/Orders’;
import ProductsComponent from ‘./panel-parts/Products’;

class App extends React.Component{
render(){
return(













);
};
};

export default App;

AND

import React from ‘react’;
import { BrowserRouter, Link } from ‘react-router-dom’;

class Sidebar extends React.Component{
render(){
return(



Andrius Avlas



<Link to="/products" onClick={()=>history.push(’/products’)}>Products
<Link to="/orders" onClick={()=>history.push(’/orders’)}>Orders
<Link to="/customers" onClick={()=>history.push(’/customers’)}>Customers



);
};
};

export default Sidebar;

Thank you for your answers in advance.


#2

Hi @andriiiiius

There’s no code in your render functions and I suspect that the issue is somewhere in there. I need that code to see if everything in that function is fine. Anyway it seems we can already fix some things that for sure break the Link functionality:

Any error during the ‘onclick’ will make the page refresh. So please work down this list carefully:

<Link to="/products" onClick={()=>history.push(’/products’)}>Product

These tags need to be closed, and also there is no need for the onClick handler. The Link component handles exactly what you are trying (if correctly implemented). So please change it to this:

<Link to="/products">Products</Link>
<Link to="/orders">Orders</Link>
<Link to="/customers">Customers</Link>

Each Link component needs to be a direct or indirect child of the BrowserRouter. This means your App.jsx render function should look similar to below:

Note that Navbar might contain your Link stuff

<BrowserRouter>
   <Navbar />

   <Switch>
     <Route path="/products" component={ProductsPage} />
   </Switch>
</BrowserRouter>

If these steps don’t work, consider marking “Preserve logs” in your Chrome Developer console. Do this by opening the Chrome dev tools, go to the ‘Console’ tab. On the right side there is a ‘gear’ icon. Click it and switch on “Preserve logs”. Now try clicking your link and see if any error appears. Fixing any error that appears on the click action should fix your problem.

If not, return and I’m happy to help, but please next time wrap your code in markdown code tags ``` Like this:

    ```
    code here
    ```

Good luck!