react-router
A complete routing solution for React.js
React Router Documentation
Any way to prevent /#/
from showing in the browser's address bar when using react-router? That's with ReactJS. i.e. Clicking on links to go to a new route shows localhost:3000/#/
or
localhost:3000/#/about
. Depending on the route.
Source: (StackOverflow)
Very similar to this angular question: how do I use anchor links for in-page navigation when using react-router?
In other words, how do I implement the following plain HTML when using react-router?
<a rel='nofollow' href="#faq-1">Question 1</a>
<a rel='nofollow' href="#faq-2">Question 2</a>
<a rel='nofollow' href="#faq-3">Question 3</a>
<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>
Currently I intercept clicks on such links, and scroll to the anchor position. This isn't satisfactory, because it means it's impossible to link directly to some section of a page.
Source: (StackOverflow)
I'm using React-router and it works fine while I'm clicking into link buttons, but when I refresh my webpage it does not load what I want.
For instance, I am into localhost/joblist and everything is fine because I arrived here pressing a link. But If I refresh the webpage I get: Cannot GET /joblist
By default It didn't work like this. Initially I had my URL: localhost/#/ and localhost/#/joblist and they worked perfectly fine. But I don't like this kind of url, so trying to erase that '#' I wrote:
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
This problem does not happen with localhost/, this one always returns what I want.
EDIT: This app is single-page, so /joblist don't need to ask anything to any server.
EDIT2: My entire router.
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="joblist" path="/joblist" handler={JobList}/>
<DefaultRoute handler={Dashboard}/>
<NotFoundRoute handler={NotFound}/>
</Route>
);
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(<Handler/>, document.body);
});
Source: (StackOverflow)
I am trying to use the react-router but when I write a simple route doesn't work and the console show Uncaught TypeError: Cannot read property 'toUpperCase' of undefined.
Otherwise when I use without the react-router that work well
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var App = React.createClass({
render: function () {
return (
<div>Hello World</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App} />
</Router>
), document.body);
The error is from this line of the react library
function autoGenerateWrapperClass(type) {
return ReactClass.createClass({
tagName: type.toUpperCase(), //<----
render: function() {
return new ReactElement(
type,
null,
null,
null,
null,
this.props
);
}
});
}
Source: (StackOverflow)
I am new to react-router (https://github.com/rackt/react-router). I included it after react like this:
<script src="http://fb.me/react-0.12.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactrouter/0.13.2/ReactRouter.js"></script>
I got an error:
Uncaught TypeError: Super expression must either be null or a function, not undefined
What did I do wrong?
Source: (StackOverflow)
I'm creating an app that uses webpack-dev-server in development alongside react-router.
It seems that webpack-dev-server is built around the assumption that you will have a public entry point at one place (i.e. "/"), whereas react-router allows for an unlimited amount of entry points.
I want the benefits of the webpack-dev-server, especially the hot reloading feature that is great for productivity, but I still want to be able to load routes set in react-router.
How could one implement it such that they work together? Could you run an express server in front of webpack-dev-server in such a way to allow this?
Source: (StackOverflow)
I have such structure of my React.js app with ReactRouter (https://github.com/rackt/react-router):
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
I want to pass some properties into Comments
component
(normally like <Comments myprop="value" />
)
What's the easiest and right way to do so with ReactRouter?
Source: (StackOverflow)
I am thinking and confused with the routing between Client and Server.
Support I use ReactJS for server-side rendering before sending the request back to web browser and use react-router as a client-side routing to switching between pages without refresh as SPA.
What comes to me is:
how the routes are interpreted, for example,
from homepage (/home) when requests to Post page (/posts)
Where does the routing go, on server-side or client?
How does it know or how is it processed?
Thank you.
Source: (StackOverflow)
Sometimes, when using React libraries, such as react-router, I get this error:
Uncaught TypeError: Cannot read property 'firstChild' of undefined
/~/react-router/~/react/lib/ReactMount.js?:606
How do I fix it?
Source: (StackOverflow)
I'm attempting to port a small react app over to typescript.
I'm encountering issues with react-router. I have the latest definitions from definitely type but the following code gives me errors:
var routes:Router.Route = (
<Route name="root" path="/" handler={MyApp}>
<Route path="dashboard" handler={MyDash} />
<DefaultRoute handler={SomeSection} />
<NotFoundRoute handler={NotFoundPage} />
</Route>
);
Router.run(routes, function (Handler:React.Component<any, any>) {
React.render(<Handler/>, document.body);
});
These are the compilation errors I get:
js/app.tsx(31,3): error TS2605: JSX element type 'Component<RouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<RouteProp, any>'.
js/app.tsx(32,5): error TS2605: JSX element type 'Component<RouteProp, any>' is not a constructor function for JSX elements.
js/app.tsx(47,5): error TS2605: JSX element type 'Component<DefaultRouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<DefaultRouteProp, any>'.
js/app.tsx(49,5): error TS2605: JSX element type 'Component<NotFoundRouteProp, any>' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Component<NotFoundRouteProp, any>'.
js/app.tsx(53,20): error TS2345: Argument of type '(Handler: Component<any, any>) => void' is not assignable to parameter of type '(Handler: RouteClass, state: RouterState) => void'.
Types of parameters 'Handler' and 'Handler' are incompatible.
Type 'Component<any, any>' is not assignable to type 'RouteClass'.
js/app.tsx(54,17): error TS2604: JSX element type 'Handler' does not have any construct or call signatures.
What is the correct way to initialize a set of react-router routes using typescript?
(I should clarify that I'm using a nightly typescript build which has support for JSX via the --jsx react
flag
Source: (StackOverflow)
I am using react-router with the flux architecture (facebook's flux implementation).
Currently in my system I have route that says "chat/:topic".
When the user is entering this component, I am creating a subscription (using action creation, on componentWillMount) to a websocket server, and I am removing the subscription on componentWillUnmount.
When the user is moving to another route the whole workflow works alright - because react-router is unmounting my component.
When I transition inside my route (from "chat/games" to "chat/tv"), the component isn't mounted and I need to clear my state of the components.
I read about different actions that I can take and this on transition to dispatch an action "TRANSITION" and every relevant store will clear it's store.
In my opinion, this kind of action - is wrong, it couples my stores and my router.
How would you solve this problem? Is this an issue that I should raise to react-router and ask them to unmount inside my route?
Source: (StackOverflow)
I'm learning React and using React-router. The app I'm building is a mobile style app with a top navigation menu, and a content section below. As I navigate the app pages I'd like to add a page 'title' to the menu bar to identify which page you are currently on.
My routes:
<Routes>
<Route name='home' path='/' handler={HomePage}>
<Route name='product-list' path='products/' handler={ProductList}/>
<Route name='product-detail' path='product/:slug/' handler={ProductDetail} addHandlerKey={true}/>
</Route>
</Routes>
HomePage.render:
<div className="container">
<NavigationMenu />
<div className="contents">
{this.props.activeRouteHandler()}
</div>
</div>
NavigationMenu.render:
<div className="navigationMenu">
<div className="navigationMenuTitle>{this.props.title}</div>
</div>
My issue
The child routes to HomePage need to set their title based on content returned from an Ajax call.
I had thought to add callbacks to each route, passing title back to their parent class which could in turn pass this data to the NavigationMenu. Unfortunately this does not work: As you navigate through the pages, the only function that is repeatedly called is render and setting state here raises an Invariant Violation
error.
My questions
- Is there a better way of managing the title?
- Are there any alternatives for tracking the current page than relying on the routes render function passing data to a callback (this seems dirty) each time?
Source: (StackOverflow)
I am having a nightmare finding a good solution for testing a React Router link. It is passing on the 'renders Categories properly' however zero links are being passed through to the test, I have tried so many different things and have still got nowhere.
Below is what i am trying to test:
Component
import React from 'react';
import { Link } from 'react-router';
class Categories extends React.Component {
constructor(props, context){
super(props);
context.router
}
render() {
return (
<nav className="categories">
<ul>
<li><Link to="devices">Devices</Link></li>
<li><Link to="cases">Cases</Link></li>
<li><Link to="layouts">Layouts</Link></li>
<li><Link to="designs">Designs</Link></li>
</ul>
</nav>
);
}
}
Categories.contextTypes = {
router: React.PropTypes.func.isRequired
};
export default Categories;
StubRouterContext
import React from 'react';
import objectAssign from 'object-assign';
var stubRouterContext = (Component, props, stubs) => {
function RouterStub() { }
objectAssign(RouterStub, {
makePath () {},
makeHref () {},
transitionTo () {},
replaceWith () {},
goBack () {},
getCurrentPath () {},
getCurrentRoutes () {},
getCurrentPathname () {},
getCurrentParams () {},
getCurrentQuery () {},
isActive () {},
getRouteAtDepth() {},
setRouteComponentAtDepth() {}
}, stubs)
return React.createClass({
childContextTypes: {
router: React.PropTypes.func,
routeDepth: React.PropTypes.number
},
getChildContext () {
console.log('blah');
return {
router: RouterStub,
routeDepth: 0
};
},
render () {
return <Component {...props} />
}
});
};
export default stubRouterContext;
Component Test
var expect = require('chai').expect;
var React = require('react/addons');
var Categories = require('../app/src/js/components/Categories.React.js');
var stubRouterContext = require('../test-utils/stubRouterContext.js');
var TestUtils = React.addons.TestUtils;
describe('Categories', function() {
var categoriesWithContext = stubRouterContext(Categories);
it('renders Categories properly', function() {
var categories = TestUtils.renderIntoDocument(<categoriesWithContext />, {});
});
it('renders 4 links', function() {
var catLinks = TestUtils.scryRenderedDOMComponentsWithTag(categoriesWithContext, 'a');
expect(catLinks).to.have.length(4);
});
});
Source: (StackOverflow)
I'm currently trying to add Jest tests to a React application (found here).
However, when I run the following test,
/** @jsx React.DOM */
jest.dontMock('jquery');
jest.dontMock('../js/components/CategoryPage.jsx');
describe('Category Page', function() {
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var CategoryPage = require('../js/components/CategoryPage.jsx');
it('renders into the page correctly', function() {
// Render the CategoryPage into the document
var categoryPage = TestUtils.renderIntoDocument(
<CategoryPage params={{"category": "tests"}} />
);
expect(categoryPage).toBeDefined();
});
});
I get the following error:
● Category Page › it renders into the page correctly
- TypeError: Property 'makeHref' of object #<Object> is not a function
at Navigation.makeHref (/home/stephen/reps/node_modules/react- router/modules/mixins/Navigation.js:29:25)
at React.createClass.getHref (/home/stephen/reps/node_modules/react-router/modules/components/Link.js:76:17)
at React.createClass.render (/home/stephen/reps/node_modules/react-router/modules/components/Link.js:97:18)
at ReactCompositeComponentMixin._renderValidatedComponent (/home/stephen/reps/node_modules/react/lib/ReactCompositeComponent.js:1260:34)
at wrapper [as _renderValidatedComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactCompositeComponentMixin.mountComponent (/home/stephen/reps/node_modules/react/lib/ReactCompositeComponent.js:802:14)
at wrapper [as mountComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/home/stephen/reps/node_modules/react/lib/ReactMultiChild.js:195:42)
at ReactDOMComponent.Mixin._createContentMarkup (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:260:32)
at ReactDOMComponent.Mixin.mountComponent (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:182:14)
at ReactDOMComponent.wrapper [as mountComponent] (/home/stephen/reps/node_modules/react/lib/ReactPerf.js:50:21)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/home/stephen/reps/node_modules/react/lib/ReactMultiChild.js:195:42)
at ReactDOMComponent.Mixin._createContentMarkup (/home/stephen/reps/node_modules/react/lib/ReactDOMComponent.js:260:32)
Both my app and the CategoryPage
component specifically use react-router. The CategoryPage contains a mixin which uses react-router for authentication. Based on my own debugging, I have found that the error is occurring when Jest tries to call makeHref
, one of react-router's built-in methods for Navigation.
To fix this, I first tried calling jest.dontMock('react-router')
, but this did not have any effect. The problem seems to be that, by not mocking CategoryPage
, jest will automatically and irreversibly include all of its dependecies, unmocked.
Part of the reason this issue is so difficult to solve is because most people using Jest with React seem to not be testing their components, either because they are not as test-focused or because they are using Flux and only testing Stores, Dispatchers, etc. We are not yet using Flux, so this is not an option for us, but may be something we have to transition to in the future.
EDIT 1: The test passes if I remove the jest.dontMock('../js/components/CategoryPage.jsx')
but then it is impossible to actually test the functionality of that component.
EDIT 2: When I exclude jest.dontMock('jquery')
I get another error related to the mixin I use to create Modals:
Category Page › it encountered a declaration exception
- TypeError:
/home/stephen/reps/js/components/CategoryPage.jsx:
/home/stephen/reps/js/components/Feed.jsx:
/home/stephen/reps/js/components/InvestmentButton.jsx:
/home/stephen/reps/js/components/Modal.jsx:
/home/stephen/reps/js/mixins/BootstrapModalMixin.jsx:
/home/stephen/reps/node_modules/bootstrap/dist/js/npm.js:
/home/stephen/reps/node_modules/bootstrap/js/alert.js: Cannot call method 'on' of undefined
EDIT 3: I have seemingly isolated the bug to react-router's Navigation mixin, where it calls this.context.makeHref
. The React team has deprecated this.context
since version .9 so I believe this may be the source of the problems. Thus, any work-around or fix for this.context
is welcome.
Source: (StackOverflow)