Browser Router from React-Dom not working - javascript

I am attempting to serve a react app from the public folder of my rails app. I am building the js file and putting it in the public folder. When I go to the root of the app, I can see that the js and my index.html page have loaded. However, when I try to go to page, like /landing, I get a 404, route not found from Rails. I can't figure out why the react router is not kicking in. This all works on dev where I am serving the react app with a second server, I only get this issue in production. Any suggestions?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.scss';
ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React from 'react';
import Auth from './util/auth';
import { Redirect, BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import MyAccount from './components/my_account';
import MyListings from './components/my_listings';
import LoginPage from './components/login_page';
import LandingPage from './components/landing_page';
import RegistrationForm from './components/registration_form';
import PasswordResetForm from './components/password_reset_form';
import RequestPasswordResetForm from './components/request_password_reset_form';
import {FlashMessages} from './components/flash_messages';
import $ from 'jquery';
import popper from 'popper.js';
import './stylesheets/App.css';
window.Popper = popper;
window.jQuery = $;
window.$ = $;
global.jQuery = $;
require('bootstrap');
const App = appProps => (
<div>
<div id="flash-messages">
<FlashMessages />
</div>
<Router>
<div className="App">
<Switch>
<Route exact name="index" path="/landing" component={LandingPage} />
<Route exact name="login" path="/login" component={LoginPage} />
<Route exact name="register" path="/register" component={RegistrationForm} />
<Route exact name="reset_password" path="/reset_password" component={PasswordResetForm} />
<Route exact name="reset_password_request" path="/reset_password_request" component={RequestPasswordResetForm} />
<PrivateRoute path="/my_account" component={MyAccount}/>
<PrivateRoute path="/my_listings" component={MyListings}/>
</Switch>
</div>
</Router>
</div>
);
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
Auth.isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
export default App;

A typical gotcha with React Router is that you need to return the same index.html page for all routes - be it /, /landing-page/ or /a/really/deep/route/.
You typically solve that by adding a catch-all route. I don't know rails all that well, but I think this answer might help you out.

The problem is that all routes handled first by rails and he redirects you to the page where your react routers are. And you have only one HTML page that contains your react.js code.
When you go to /login or any other page you get err 404 because you don't have a route in rails to handle it.
You need to add rails routes for all your pages and redirect them to the same index page
Or do a catch all routes to the same index page

There's some documentation for configuring your server. Basically you always need to return index.html with a 200 status code.
https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md#configuring-your-server

Related

React route paths not working in Static Spring Boot folder

I've made a front end in reactjs and back end of application in Spring Boot. When I do npm run build and build a static version of the app to put it in the static folder of Spring Boot application, my Route Paths in react stop working. When I try to get to localhost:8080/choose or localhost:8080/account it says 404 not found, but in normal front end application it works correctly.
import React, {useEffect, useState} from 'react'
import logo from './logo.svg';
import './App.css';
import GoogleLogin from "react-google-login";
import {BrowserRouter, Routes, Route, Navigate} from "react-router-dom";
import Choose from "./Choose/Choose.js";
import Main from "./Main/Main.js";
import Account from "./Account/Account.js";
function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path={'/'} element={
<Main></Main>
}
>
</Route>
<Route path={'/choose'} element={
<Choose></Choose>
}>
</Route>
<Route path={'/account'} element={
<Account></Account>
}>
</Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;

My react app doen't display any content after I deploy it on digital ocean

I've successfully deployed my react app on digital ocean as a static site. But when I click to see the live app the link only shows me a blank page, instead of show me the landing page (dashboard).
The command I used for the build
npm build
The code in my index.js file
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
// core components
import Admin from "layouts/Admin.js";
import RTL from "layouts/RTL.js";
import "assets/css/material-dashboard-react.css?v=1.9.0";
import 'bootstrap/dist/css/bootstrap.min.css';
const hist = createBrowserHistory();
ReactDOM.render(
<Router history={hist}>
<Switch>
<Route path="/admin" component={Admin} />
<Route path="/rtl" component={RTL} />
<Redirect from="/" to="/admin/dashboard" />
</Switch>
</Router>,
document.getElementById("root")
);
my project structure
[1]: https://i.stack.imgur.com/JL2Yi.png
I found the solution. I just had to edit the package.json file and change the homepage attribute like this:
"homepage": ""

How to implement links with redirect in next.js?

I have the following react component which I am trying to implement in next.js.
React component:
import React from "react";
import { Route, Switch, Redirect, withRouter } from "react-router-dom";
import Dashboard from "../../pages/dashboard";
import Profile from "../../pages/profile";
function Layout(props) {
return (
<>
<Switch>
<Route
exact
path="/"
render={() => <Redirect to="/app/dashboard" />}
/>
<Route path="/app/dashboard" component={Dashboard} />
<Route path="/app/profile" component={Profile} />
</Switch>
</>
);
}
export default withRouter(Layout);
As I am very new to next. j's, I am not sure on, how can I handle the routes with redirect in next.js similar to above react component code.
Any help is appreciated?
You are using React-Router with NextJS which is possible but not the best practice.
NextJS router is a pretty complicated thing as it handles ClientSide and ServerSide routing simultaneously.
your /app/dashboard and /app/profile pages should render properly. If you want to redirect / to /app/dashboard you can use this trick inside the getInitialProps of the pages/index.js file.

react router dom can't get page

I'm using react with express using web pack but react router dom create an error i.e The null match problem.It can't get the page and the match is Null.
MY routes page code is: routes.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import App from './App.js';
import language from './language.js';
import Page from './Page.js';
const Routes = () => (
<Router>
<div>
<Route path='/' component={App} />
<Route path='/page' component={Page} />
<Route path='/language' component={language} />
</div>
</Router>
)
console.log(typeof Routes)
export default Routes;
I have created sample snippet same as your code.
But its working fine. I am not getting any error
Check out this Snippet

React installed react router but cannot get the page to render

I've installed react router and I'm trying to get the main page to render.
This is the current index.js
import React, { Component, PropTypes } from 'react';
import { Router, Route } from 'react-router';
import Layout from './components/Layout';
import NewsComponent from './components/NewsComponent';
<Router>
<div>
<Route exact path="/" component={Layout} />
<Route path="/news" component={NewsComponent} />
</div>
</Router>
const app = document.getElementById('app')
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout} />
</Router>, app);
The Layout component contains the layout of the page.
What I'm I missing?
I'm I doing this wrong?
There are some references you are missing, I dont know if you have omitted them just for this example or you are really missing them. Try this:
import React from 'react';
import ReactDOM from 'react-dom'; //Missing in your example
import {
Router,
Route,
browserHistory //Missing in your example
} from 'react-router';
import Layout from './components/Layout';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Layout} />
</Router>,
document.getElementById('root')
)
Then in your component you can even navigate through history:
import { hashHistory } from 'react-router'
//Dont forget to bind this in the constructor
yourMethod (someParams) {
hashHistory.push(someUrl)
}
Try explicitly importing ReactDOM (import ReactDOM from 'react-dom'); it isn't automatically included when you import React.
In addition to modifying your code [missing imports, etc.], you'd want to specifically mention the version of the react-router you are using. Assuming that you are using NPM
Try:
npm remove react-router
Then:
npm install --save react-router#3.0.0
React-router V4, which is installed by default, is a complete re-envisioning of the react-router and is not compatible with the codes written for the previous versions of react-router.
If you haven't used React in a while, I suggest you use create-react-app. Starting from there will be quite straightforward:
https://github.com/facebookincubator/create-react-app

Categories