react-router Cannot GET /route - ecmascript-6

Ok, guys, here's the problem... I've been writing code for my web application using another fluently working app as an example for the beginning. Here is the source code:
(./app.jsx)
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import App from './components/app';
import Signin from './components/auth/signin';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory}>
<Route path='/' component={App}>
<Route path='signin' component={Signin} />
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
(./components/app.js)
import React, { Component } from 'react';
import Header from './header';
export default class App extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
}
(./components/auth/signing.js)
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
class Signin extends Component {
handleFormSubmit({ email, password }) {
console.log(email, password);
}
render() {
const { handleSubmit, fields: { email, password }} = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Email</label>
<input {...email} className="form-control"/ >
</fieldset>
<fieldset className="form-group">
<label>Email</label>
<input {...password} className="form-control"/ >
</fieldset>
<button action="submit" className="btn btn-primary">Sign in</button>
</form>
);
}
}
export default reduxForm({
form: 'signin',
fields: ['email', 'password']
})(Signin);
(you can see my whole repository here: https://github.com/LiJuons/react-dribbble )
The thing is that when I go to localhost:3000 - everything's Ok, but when I enter localhost:3000/signin - I get error message that says "Cannot GET /signin" THOUGH the application I'm taking code from works properly and shows form!
The problem is in routes, because if I set signin.js route's path to '/' in my project, form is shown on home directory without any problem.
Package.json files are the same in both projects (same number of packages, same versions and dependencies), only start script differs, so...
THE ONLY DIFFERENCE between the working project and mine is that in working one 'npm start' script is defined as:
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js"
where in mine it's:
"start": "node server.js"
P.S. I checked every line to be sure that code of both projects would be as homogeneous as possible.
Any suggestions how to fix this issue?
Thank you

Your server is probably not configured to support HTML5 history.
Take a look at https://medium.com/#baphemot/understanding-react-deployment-5a717d4378fd
React-router not working when typing URL manually
This is a common surprise and is related to the fact that you are using browserHistory in your application, which requires some additional configuration of the server itself. Basically, when you type the URL by hand, by default the server will look for a file with that path, stored on its disk — if not found, it will show a 404 error. What you want to do is internally redirect the request to the index of your application.
You can see the documentation for react-router v3 about this setting (don’t worry, it’s still valid for react-router 4!). Common configuration are:
express:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// this assumes that all your app files
// `public` directory relative to where your server.js is
app.use(express.static(__dirname + '/public'))
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("Server started on port " + port);

Related

How to create a new page on Ionic with react?

I run command ionic generate pages/login but me return this error
Since you're using the React project type, this command won't work. The Ionic CLI doesn't know how to generate framework components for React
You'll have to make a new file in e.g src/pages/ (e.g. with the name xy.tsx) with the following contents:
import React from "react";
import {IonPage} from "#ionic/react";
const PageXY: React.FC = () => {
return (
<IonPage>
...
</IonPage>
);
};
export default PageXY;
and in your App.tsx aka Router you have to import it with import PageXY from "./pages/xy";
and hook it up to the Router like so: <Route path="/xy" component={PageXY} exact />
Hope this still helps someone

Unable to render html file using Route in react

I am trying to render html using Route but browser is giving me following error:
Failed to compile.
./src/hello.html 1:0 Module parse failed: Unexpected token (1:0) You
may need an appropriate loader to handle this file type.
<html> | Hello | </html>
I have already tried using babel but when I run npm start the terminal is telling me undo all the babel and webpack changes -
Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
Delete node_modules in your project folder.
Remove "babel-loader" from dependencies and/or devDependencies in the package.json file in your project folder.
Run npm install or yarn, depending on the package manager you use.
In most cases, this should be enough to fix the problem. If this
has not helped, there are a few other things you can try:
If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead. This may help because npm has known issues with package hoisting which may get resolved in future versions.
Check if /Users/shubhamnandanwar/Desktop/react/YourHourWebApp/node_modules/babel-loader is outside your project directory. For example, you might have accidentally installed something in your home folder.
Try running npm ls babel-loader in your project folder. This will tell you which other package (apart from the expected react-scripts) installed babel-loader.
This is my App.js file
import React, { Component } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Navbar from "./components/layout/Navbar";
import Dashboard from "./components/dashboard/Dashboard";
import UserStory from "./components/stories/UserStory";
import SignIn from "./components/auth/SignIn";
import SignUp from "./components/auth/SignUp";
import CreateStory from "./components/stories/CreateStory";
import { Redirect } from "react-router-dom";
class App extends Component {
reload = () => window.location.reload();
render() {
return (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/" component={TemplateHTMLComponent} />
<Route exact path="/stories" component={Dashboard} />
<Route path="/story/:id" component={UserStory} />
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
<Route path="/uploadStory" component={CreateStory} />
</Switch>
</div>
</BrowserRouter>
);
}
}
class TemplateHTMLComponent extends React.Component {
htmlFile = require("./hello.html");
render() {
return <div dangerouslySetInnerHTML={{ __html: this.htmlFile }} />;
}
}
export default App;
I am new in react and have spent hours trying to fix it. Can anyone please give me some direction
1) First of all install html-loader module.
npm install --save-dev html-loader
2) Inside webpack.config.js
{
modules: {
loaders: [
{ test: /\.html$/, loader: 'html' }
]
}
}
3) Correct the calling component
import htmlFile from './hello.html';
class TemplateHTMLComponent extends React.Component {
render() {
return <div dangerouslySetInnerHTML={{ __html: this.htmlFile }} />;
}
}
Hope that helps!!!
please put 'htmlFile = require("./hello.html");' line on the top outside the class.
const htmlFile = require("./hello.html");
class TemplateHTMLComponent extends React.Component {
render() {
return <div dangerouslySetInnerHTML={{ __html: this.htmlFile }} />;
}
}
Make sure your html is a string. Read more here https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
Then export it from a .js file like this:
// inside hello.js file
// using es6 syntax
export default `<html> | Hello | </html>`
or
// inside hello.js file
// using older syntax
module.exports = `<html>blah blah</html>`
then import it:
import htmlFile from 'htmlFile'
or
const htmlFile = require('hello')

react-snap and react-router together make a problem

I need to start a react application and I need pre-rendering and routing, so I installed react-snap and react-router. (The react-router to do the routing and react-snap for pre-rendering obviously).
Everything looks fine in the local with 'npm start' but as I make a production build and serve it, the routing links make the page redirect to a new url, so all i see always, is the homepage.
My render looks like this:
render() {
return (
<Router>
<React.Fragment>
<MainNav/>
<Route exact path="/" component={Home}/>
<Route path="/greeting/:name/:surname" render={(props) => <Greetings text="Hello, " {...props} />} />
<Route path="/About" component={About}/>
</React.Fragment>
</Router>
);
}
and this is my index.js as suggested by react-snap
import React from 'react';
import { hydrate, render } from "react-dom";
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
const rootElement = document.getElementById("root");
if (rootElement.hasChildNodes()) {
hydrate(<App />, rootElement);
} else {
render(<App />, rootElement);
}
serviceWorker.unregister();
any ideas?
I've been able to fix a similar issue by adding the following snippet to my package.json
"reactSnap": {
"fixWebpackChunksIssue": false
}
Check the following link for more information and other options
https://github.com/stereobooster/react-snap/issues/264
I've been battling this for a couple weeks now. The main thing I've noticed is that if I call registerServiceWorker() in index.js, the app will function normally after building. If I comment out this line the app only routes to '/' no matter what.
It appears you are unregistering the service worker in your index.js, this might cause an issue.
A catch 22 I've run into and haven't been able to solve is that if I use the registerServiceWorker() call in index.js, react-snap doesn't properly prerender all the routes, and if I do comment out the registerServiceWorker() line, react-snap prerenders all routes perfectly, but the app doesnt navigate.
It's also worth noting that my project was created using 'create-react-app' and hasnt been ejected.

How to use react React Router with React VR?

I'm trying to figure out how to plug React Router with React VR.
First, should I use react-router dom / native? it's not clear since React VR builds on top of React Native, but runs in the browser.
This is the code I'm having issues with.
import React from 'react';
import { AppRegistry } from 'react-vr';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import Landing from './components/Landing';
import Video from './components/Video';
export default class WelcomeToVR extends React.Component {
render() {
return (
<Router>
<Route exact path={'/vr/'} component={Landing} />
<Route exact path={'/vr/video/'} component={Video} />
</Router>
);
}
};
AppRegistry.registerComponent('WelcomeToVR', () => WelcomeToVR);
The above code returns the following errors when opening the browser on /vr/:
I come with this solution based on Ryan Florence video mentioned by remydib using react-router 4.1.2.
In main app component:
import { MemoryRouter, Redirect, Route, Switch } from 'react-router';
...
<MemoryRouter>
...
</MemoryRouter>
In the component using VrButton:
export class NavBtn extends React.Component {
static contextTypes = {
router: React.PropTypes.object.isRequired,
};
render() {
const { to } = this.props;
const onClick = () => this.context.router.history.push(to);
return (
<VrButton onClick={onClick}>
...
</VrButton>
);
}
}
There is react-router-vr package in npm, but it looks like placeholder only. Sadly at the moment there is no support for browser URL.
Ryan Florence, the author of React Router, explains how he does it here: https://twitter.com/ryanflorence/status/808890440929771520
I don't know of a library though.
React-VR does not use the normal history APIs of other applications. Memory Router is the option listed above, but I recommend conditional rendering.
You can use the History API from Native Modules instead to load information into the URL.

how to pass value to the root query in react-router-relay

Suppose that I have the following root query in a relay with react-router-relay project:
export default {
calc: () => Relay.QL`query queryType ($number: String) { auth (number: $number) }`,
}
Initial value of $number comes from server like a hidden input and I want to use this number in my first query to server. How can I pass $number to my query using the current react-router-relay API? This is neither a queryParam or stateParam.
You should be able to do something like:
import {createHistory} from 'history';
import React from 'react';
import ReactDOM from 'react-dom';
import {Route, Router} from 'react-router-relay';
import MyComponent from './components/MyComponent';
import MyComponentQueries from './routes/MyComponentQueries';
function addAuthParam(params, route) {
return {
...params,
number: 'SECRET',
};
}
ReactDOM.render(
<Router
history={createHistory()}
createElement={ReactRouterRelay.createElement}>
<Route
component={MyComponent}
path="/thing/:id"
prepareParams={addAuthParam}
queries={MyComponentQueries}
/>
</Router>,
document.getElementById('relay-root')
);
prepareParams was added in react-router-relay in v0.6.2. The above syntax should work for that or v0.7.0 (the current release) as well.