React router - page does not render until I do a browser refresh - javascript

I have tried to decouple my components a bit more and I ran into this weird bug. I obscured the other general imports. All components import properly and work.
What happens is I land on "/", then I click a button to navigate to dashboard it's a blank page (the URL did change). Then I hit refresh in my browser and the correct component displays. This also happens if I go back to my landing page; it's blank until I refresh.
In my app component
import history from './services/history';
import Routes from './routes';
function App() {
return (
<Router history={history}>
<Routes />
</Router>
);
my history component (super simple)
import { createBrowserHistory} from 'history';
const history = createBrowserHistory();
export default history;
and finally my routes:
import Landing from "../pages/landing/landing.page"
import Dashboard from "../pages/dashboard/dashboard.page.jsx"
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={Landing}/>
<Route path="/dashboard" component={Dashboard}/>
</Switch>
);
Here is my landing page, which I click the button to navigate to "/dashboard"
import { Link } from "react-router-dom";
function Landing () {
return (
<div class="landing-container">
<Link to="/dashboard"><button> Setup Tests </button></Link>
</div>
)
}
export default Landing;

It looks like you're now using Router from react-router-dom. From my understanding, you have to import BrowserRouter in terms of browser use. So your code would look like:
import { BrowserRouter } from "react-router-dom";
function App() {
return (
<BrowserRouter history={history}>
<Routes />
</Router>
);
}

Related

React Router Dom (v 6.4.3) page becomes unresponsive after navigation

My page is becoming unresponsive when I try to navigate using useNavigate or a Link in my component. After clicking a button or link, the url will change, and the javascript inside the target component will execute, but the page does not re-render. useNavigate works with other components in my app, so I'm not quite sure what the issue is. Any input would be appreciated!
Dashboard.js:
import { useNavigate, Link } from "react-router-dom";
const Dashboard = () => {
console.log("hello from dashboard");
let navigate = useNavigate();
return (
<div>
<Link className="pl-20" to="/test">
test
</Link>
</div>
);
};
export default Dashboard;
Test.js:
import React from "react";
const Test = () => {
console.log("hello from test page");
return <div>this is the test page</div>;
};
export default Test;
App.js:
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Dashboard from "./pages/Dashboard";
import Test from "./pages/Test";
function App() {
return (
<>
<Nav />
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/test" element={<Test />} />
</Routes>
</>
);
}
gif showing the issue
you gave pl-20 class on Dashboard. but not on Test component.
Please check.

React.js routing keeps rendering my main App regardless of URL

I am running an issue where, regardless of what URL I am putting into my browser, I keep getting routed to my main page. I've posted the code below for you to take a look, but my goal is to have my browser take me to my drivers.jsx component when the URL is localhost:3000/drivers. Currently, when I go to localhost:3000/drivers, it renders my _app.jsx component instead :(. Can someone help me understand why I can never render the Drivers component (in drivers.jsx) when I am at localhost:3000/drivers?
index.jsx:
import { BrowserRouter as Router, Routes, Switch, Route } from 'react-router-dom';
import MyApp from './_app.jsx';
import Drivers from './drivers.jsx'
import React, { Component } from 'react'
import { Link } from "../routes.js"
class Home extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/drivers' element = {<Drivers />}> </Route>
<Route exact path='/' element = {<MyApp />}> </Route>
</Switch>
</Router>
);
}
}
export default Home;
_app.jsx
import React, { Component } from 'react';
import { useLoadScript } from '#react-google-maps/api';
import Map from '../components/map.jsx';
import "../styles/globals.css";
const MyApp = () => {
const libraries = ['places'];
const {isLoaded} = useLoadScript({
googleMapsApiKey: XXXXXXXXXXXXXX,
libraries
});
if (!isLoaded) return <div>Loading...</div>;
return (
<Map />
);
}
export default MyApp;
drivers.jsx
import React, { Component } from 'react';
class Drivers extends Component {
render() {
return (
<div>TEST</div>
);
}
}
export default Drivers;
I've tried putting the routing logic inside _app.jsx instead, but that causes an incredible amount of errors. My thought is index.js should host all the routing logic, but it shouldn't keep rendering MyApp instead of Drivers when the route is "localhost:3000/drivers".
if your react-router-dom version is
6.4.3
then the switch component dosen't work try changing code to this
instead of using Switch. wrap Route inside Routes
<Router>
<Routes>
<Route path='/drivers' element = {<Drivers />}> />
<Route exact path='/' element = {<MyApp />}> />
</Routes>
</Router>
like this

React-router-dom Link changes URL without rendering component

I have a Main component that looks like this:
import React from 'react';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router-dom';
import store from '../store';
import history from '../store/history';
import SideBar from './SideBar';
import { ConnectedUsers } from './UsersPage';
const Main = () => (
<Router history={history}>
<Provider store={store}>
<div>
<SideBar/>
<Route
exact
path="/users"
render={ () => (<ConnectedUsers/>)}
/>
</div>
</Provider>
</Router>
);
export default Main;
It uses a navigation component which I've named SideBar:
import { Link } from 'react-router-dom';
import React from 'react';
const SideBar = () => (
<div>
<Link to="/users">
<h1>Users</h1>
</Link>
</div>
);
export default SideBar;
This doesn't work. When I click on the Users link on the page in the browser, the URL changes to the correct one (localhost:8080/users) but the page remains blank. The component doesn't render. If I put the URL localhost:8080/users manually in the address bar in the browser the component renders correctly.
After some searches, I found people recommending to implement the routes like this:
import React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, withRouter } from 'react-router-dom';
import store from '../store';
import history from '../store/history';
import SideBar from './SideBar';
import { ConnectedUsers } from './UsersPage';
const Main = () => (
<Router history={history}>
<Provider store={store}>
<div>
<SideBar/>
<Route exact path="/users" component={withRouter(ConnectedUsers)}
/>
</div>
</Provider>
</Router>
);
export default Main;
But this also didn't work for me. The exact same propblem remains—the /users page renders correctly when I manually type in the URL in the address bar, but comes up blank if I navigate to that URL using the Link.

React redirection rendering a blank page

I have a React application running in production. When i am on, lets say /contacts page, an API call is made and if it returns a 404, i redirect the user to an error page ( /error ).
The redirection is happening to /error. I can see it in the url. But the issue is that the page rendered is a blank page. I don't know why. Please note I see one error in such scenario 'ChunkLoadError: Loading chunk 16 failed'
Below is the main pieces of code I have.
// In the index.js
import React, { useEffect, Suspense } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { createBrowserHistory } from "history";
const Contact = React.lazy(() => import("./pages/Contact"));
const Error = React.lazy(() => import("./pages/Error"));
function App() {
const history = createBrowserHistory({
basename: process.env.PUBLIC_URL
});
return (
<Router basename={"LB"} history={history}>
<div>
<div>
<Suspense fallback={"Loading..."}>
<Route path="/contact" exact component={Contact} />
<Route path="/error" component={Error} />
</Suspense>
</div>
</div>
</Router>
);
}
export default App;
// Inside the Contact page
axios.get(url)
.then((response)=>{console.log('success')})
.catch((error)=>{props.history.push("/error");})
Any suggestions or reason why this is happening?

How can I use history.push( ) and call a function at the same time?

I want to implement a button, in the AppBar provided by Material UI, that when clicked, it redirects me to a new page (from '/' to '/login'). So, I used history.push( ) and it works. But, the page does not render another component that it should display. The component is a function. How can I make this work?
I'm new to ReactJS and I'm using stuff from Material-UI so I don't how to tweak things to my favor.
It's a lot of code, so I made a working example for those who want to see what I mean:
https://codesandbox.io/embed/6jmlxlj3wz?fontsize=14
A few things:
In your App.js you are passing history to Router but you haven't imported it...
import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import Login from './components/Login';
import history from './history'; // import it to use it
class App extends Component {
render() {
return (
<Router history={history}>
<div className="App">
<Switch>
<Route exact path="/" component={Home} /> // notice I also added exact
<Route path="/login" component={Login} />
</Switch>
</div>
</Router>
);
}
}
export default App;
And here is your Home.js cleaned up... (no need for the handleClick function...)
function gotoLogin() {
history.push('/login');
}
function ContainedButtons(props) {
const { classes } = props;
return (
<div>
<Button
variant="contained"
color="secondary"
className={classes.button}
onClick={gotoLogin}
>
Login
</Button>
</div>
);
}
See a working demo here: https://codesandbox.io/s/ovwrm11wl5
Use react-router-dom to manage your routes and for history.push functionality. Its support for React is built in so it will be a much more declarative coding experience for you.

Categories

Resources