Using React-Router in ES5, I have the below code
var React = require('react');
var Render = require('react-dom').render;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var hashHistory = Router.hashHistory;
var browserHistory = Router.browserHistory;
var About = require('./components/about/aboutPage');
var routes = (
<Router>
<Route path="/" handler={App}>
<Route path="about" handler={About}/>
</Route>
</Router>
);
module.exports = routes;
This is rendered in {main.j} as
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var routes = require('./routes');
ReactDOM.render(<Router>{routes}</Router>, document.getElementById('app'));
However, in the console, am getting this warning and nothing loads up:
bundle.js:1845 Warning: [react-router] `Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead
I have clearly passed {hashHistory} in the code above, but still it keeps on complaining.
Any hints on what could be going wrong?
Thanks
No you didn't.You have just defined it and not used it. You have to pass history={hashHistory} in the router Tag.
var React = require('react');
var Render = require('react-dom').render;
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var hashHistory = Router.hashHistory;
var browserHistory = Router.browserHistory;
var About = require('./components/about/aboutPage');
var routes = (
<Router history={hashHistory}>
<Route path="/" handler={App}>
<Route path="about" handler={About}/>
</Route>
</Router>
);
module.exports = routes;
P.S. react-router 2.8.0 requires react v15.3.0 and above. Visit the
following link.
https://www.versioneye.com/nodejs/react-router/2.8.0
If you dont have this, I would suggest you use react-router v2.0.0 or update you react to the required version.
Found the reason - It was an issue with my rendering code
ReactDOM.render(<Router>{routes}</Router>, document.getElementById('app'));
as {routes} already contained {}, there was no need to specify it again whilst rendering. Because of this, ofcourse, {history} prop was missing in the render code. So, I just changed the render code to:
ReactDOM.render(routes, document.getElementById('app'));
and it works perfectly fine!
Thanks
Related
My react router is not opening my news and photos pages. When they open it's supposed to display the header file on each pages. When I try to open the news page (localhost:8080/news) I get a 404 page not found error message in my node command prompt.
My GitHub repository
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var browserHistory = ReactRouter.browserHistory;
var Header = require('./components/Header.jsx');
var News = require('./components/News.jsx');
var Photos = require('./components/Photos.jsx');
var Routes = (
<Router history={browserHistory}>
<Route path="/" component={Header}>
<Route path="news" component={News} />
<Route path="photos" component={Photos} />
</Route>
</Router>
);
module.exports = Routes;
Here's a quick answer of what you can do to your main.js file. There's probably better ways you could structure your code. I would suggest taking a closer look at more React examples around the Internet.
'use strict';
var React = require('react');
var ReactDOM = require('react-dom');
var Routes = require('./Routes.jsx');
var Header = require('./components/Header.jsx');
var Main = React.createClass({
render: function(){
return(
<div>
<Header />
<Routes />
</div>
);
}
});
ReactDOM.render(<Main />, document.getElementById('switch'));
I noticed your code seems to have a lot of duplicate files for a .js and a .jsx. You know you only need one or the other, right?
I found out I was using react-router v3.0 so I uninstalled it and installed the 2.8.1 version. It still displays the # (ie. localhost/#/news) but it's close enough. Thanks for your help.
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var useRouterHistory = ReactRouter.useRouterHistory;
var createHashHistory = require('react-router/node_modules/history/lib/createHashHistory');
var appHistory = useRouterHistory(createHashHistory)({
queryKey:false
});
var Header = require('./components/Header.jsx');
var News = require('./components/News.jsx');
var Photos = require('./components/Photos.jsx');
var Routes = (
<Router history={appHistory}>
<Route path="/" component={Header}>
<Route path="/news" component={News} />
<Route path="/photos" component={Photos} />
</Route>
</Router>
);
module.exports = Routes;
React-router is off to a really bad start... What seems basic doesn't work. Using react-router 2.0.0 my Link component updates the URL to be /about, but my page doesn't render the About component after that...
Entry point js
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var hashHistory = require('react-router').hashHistory;
var App = require('./components/App.react');
var About = require('./components/About');
ReactDOM.render(
<Router history={hashHistory} >
<Route path="/" component={App}>
<Route path="about" component={About} />
</Route>
</Router>,
document.getElementById('app')
);
App.js
'use strict';
var React = require('react');
var Link = require('react-router').Link;
var Header = require('./Header');
var UserPanel = require('./UserPanel');
var ModelPanel = require('./ModelPanel.react');
var EventPanel = require('./event/EventPanel');
var VisPanel = require('./vis/VisPanel');
var LoginForm = require('./LoginForm');
var AppStore = require('../stores/AppStore');
var AppStates = require('../constants/AppStates');
var App = React.createClass({
[... code omitted ...]
render: function() {
var viewStateUi = getViewStateUi(this.state.appState);
return (
<div>
<Header />
<Link to="/about">About</Link>
{viewStateUi}
</div>
);
}
});
For some reason, the <Link>s were not working for me with the configuration below.
// index.js
ReactDOM.render(
<Provider store={store}>
<BrowserRouter >
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
// App.js
return (
<div className="App">
<Route exact={true} path="/:lang" component={Home} />
<Route exact={true} path="/" render={() => <Redirect to={{ pathname: 'pt' }} />} />
<Route path="/:lang/play" component={Play} />} />
<Route path="/:lang/end" component={End} />
</div >
);
The Home component had the Link, but Links on the App would do the same. Every time I clicked it, it would only change the url, but the views would stay the same.
I was able to put it working when I added withRouter to the App.js
export default withRouter(connect(mapStateToProps, { f, g })(App));
I still don't understand what happened. Maybe it's related with redux or there is some detail I'm missing.
Since the 'About' route is a child of the 'App' route, you need to either add this.props.children to your App component:
var App = React.createClass({
render: function() {
var viewStateUi = getViewStateUi(this.state.appState);
return (
<div>
<Header />
<Link href="/about">About</Link>
{viewStateUi}
{this.props.children}
</div>
);
}
});
or separate your routes:
ReactDOM.render(
<Router history={hashHistory} >
<Route path="/" component={App} />
<Route path="/about" component={About} />
</Router>,
document.getElementById('app')
);
None of the solutions worked for me, including adding withRouter to my Component. I was experiencing the same issue where the browser's address bar updates the URL but the component doesn't render. During the debugging of my issue, I realize I have to present the context of my problem because it is a bit different from what the OP had.
The route I was trying to get to work was a dynamic route that takes an arbitrary parameter, e.g.
<Route path={`/hr/employees/:id`} component={EmployeePage} />
The component this route uses is "self-referential", meaning that within the component or its children components, they have a Link component that directs to /hr/employees/:id, but with a different id. So let's say if I was at /hr/employees/3 and on the page, there was a link to /hr/employees/4, e.g. <Link to='/hr/employees/4'>, I would get this problem where the component didn't re-render.
To solve this problem, I simply modified the componentDidUpdate method of my EmployeePage component:
componentDidUpdate(prevProps) {
if (this.props.match.params.id !== prevProps.match.params.id) {
// fetch data
}
}
If you're using functional components, use useEffect:
const EmployeePage = props => {
const {id} = props.match.params
useEffect(() => {
// fetch data
}, [id])
}
I am getting this error :-
Uncaught TypeError: Cannot read property 'createRouteFromReactElement' of undefined
in this code. I used Router for navigation but not working. I imported a file called Home.jsx
var React = require('react')
var ReactDOM = require('react-dom')
var Router = require('react-router').Router
var Route= Router.Route
var IndexRoute = Router.IndexRoute
var App = React.createClass({
render() {
return (
<div>
<p>App</p>
<ul>
<li>About</li>
</ul>
</div>
)
}
})
var About = require('./components/Home')
ReactDOM.render((
<Router>
<Route path="/" component={App}>
<IndexRoute path="/about" component={About} />
</Route>
</Router>
), document.body)
and Home.jsx
var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');
var Home = React.createClass({
render:function() {
return (
<RaisedButton label="Default" />
);
},
});
module.exports = Home;
There are a few things which you are doing wrong here. I'm assuming you are using React Router 1.0 (because of use of IndexRoute).
In version 1.0 Router component is a property of the top-level module, so this is how you would do your imports:
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var IndexRoute = ReactRouter.IndexRoute;
I think you also not fully understand what IndexRoute is, have a look in the docs for the clarification. But the tldr; is that the IndexRoute does not take the path argument.
Another thing is that to mount your routes components somewhere you need to specify where, and you can do it with use of {this.props.children}. So your could could look like:
var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var IndexRoute = ReactRouter.IndexRoute;
var App = React.createClass({
render() {
return (
<div>
<p>App</p>
{this.props.children}
</div>
)
}
})
var About = require('./components/Home')
ReactDOM.render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={About} />
</Route>
</Router>
), document.body)
Please have a look at the Introduction docs so you will better understand how to use react router in your app.
I can't figure out how to use any relatively recent (react 13+) version of React-router . The example on the current README suggests integrating it by rendering Router directly (with routes defined via child Route elements). Another official overview doc seems to advise using Router.run. The react-router examples use the former. None work for me: I get different errors depending on use:
When attempting to use react-router by rendering the Router element directly I get "Uncaught Error: Invariant Violation: A needs a valid Location”
When attempting to use react-router by running Router.run with routes, I get “Uncaught TypeError: Cannot read property 'toUpperCase' of null”
here is a simplified version of how to use it, this is using webpack for requires but this is irrelevant, if you have access to React and Router it will work.
var React = require('react');
var Router = require('react-router');
var DefaultRoute = Router.DefaultRoute;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var Link = Router.Link;
var Comp0 = require('./comp0.jsx');
var Comp1 = require('./comp1.jsx');
var Comp2 = require('./comp2.jsx');
var App = React.createClass({
render: function () {
return (
<div>
<div >
<li><Link to="comp0">comp0</Link></li>
<li><Link to="comp1">comp1</Link></li>
<li><Link to="comp2">comp2</Link></li>
</div>
<div>
<RouteHandler {...this.props}/>
</div>
</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="comp1" handler={Comp1}/>
<Route name="comp2" handler={Comp2}/>
<DefaultRoute name="comp0" handler={Comp0}/>
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler />, document.body);
});
I'm using react-router version 0.13.3 with react version 0.13.3 (yes both are same). I use the Router.run() way so that the UI can be re-rendered on URL change. I'll show my code that works well for me, it's in ES6 (although shouldn't be too hard to derive ES5 from it):
import React from 'react';
import Router, { Route, DefaultRoute, NotFoundRoute, Redirect, Link } from 'react-router';
// Components
import App from './components/App.js';
import Home from './components/Home.js';
import SampleComponent from './components/SampleComponent.js';
const AppRoutes = (
<Route path="/" handler={App}>
<DefaultRoute name="home" handler={Home} />
<Route name="sample" handler={SampleComponent} />
</Route>
);
Router.run(AppRoutes, Router.HashLocation, (Root) => {
React.render(<Root />, document.body);
});
Make sure the components you specify in AppRoutes is accessible (by importing or requiring them). Also in this case I've used DefaultRoute for instance in AppRoutes - so if you're using similar configurations then make sure you have them available from the react-router export. Hope that's clear.
If you're still facing issues then share your code.
I have an existing example code that you can have reference with - https://github.com/iroy2000/react-reflux-boilerplate-with-webpack
For those who are interested, it is called "React Reflux Workflow Boilerplate", and it is a workflow framework that make life easier for developers by providing a development and production ready build process framework out of the box.
I am very new to react. I tried to use react-router. But no matter how I change the code, it always give me the warning.
Warning: No route matches path "/". Make sure you have somewhere in your routes
After googling for few hours, still have no idea what is wrong. Can anyone give me some hint? Thank you
In my app.js
Router.run(routes, Router.HistoryLocation, function(Handler, routerState) {
var params = routerState.params;
React.render(
<Handler params={params}/>,
document.getElementById('react-app')
)
});
In my route.js
var routes = (
<Route name="root" path="/" handler={App}>
<DefaultRoute handler={Home} />
<Route name="commitments" handler={CommitmentList} />
<Route name="commitment" handler={Commitment} />
</Route>
);
I am also use express and tring to do server-side rendering,
module.exports = {
index: function(req, res) {
var path = req.url;
Router.run(routes, req.url, function(Handler) {
var handler = React.createElement(Handler);
var markup = React.renderToStaticMarkup(handler);
res.render('home', {
markup: markup // Pass rendered react markup
});
});
}
}
Your App handler is missing in app.js