Related
I'm using the following versions:
`"react-router": "^5.2.0",`
`"react-router-domreact-router": "^5.2.0",`
Not sure if my current setup is React-router 5 friendly or not, I was using a version prior to v5 before this.
The problem in this example is with <Route component={withTracker(InterviewContainer)} path="/interviews/companies/:companyId" /> and <Link/>
Here's my scenario:
Home page loads with a list of company links
Click on a company <Link /> which routes me to /interviews/companies/:companyId
Page loads fine, I see images, etc. for that particular company
Click browser's Back button
Click on a different company <Link /> that points to a different companyId
Problem: for #5, when the company page initially loads, it's loading with stale images and data for some reason. So in other words, I'm seeing the previous company's data & images from step #2 briefly until my React hook makes a new call to get data for this new CompanyId and repaints the browser with the right data (data for the companyId represented in the new route)
index.tsx (note the use of BrowserRouter here)
import { BrowserRouter as Router } from 'react-router-dom';
//...more code and then:
render(
<>
<div className="Site">
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
</div>
<Footer />
</>,
);
App.ts
import { Route, RouteComponentProps, Switch } from 'react-router-dom';
...more code and then here are my routes:
<Switch>
<Route component={withTracker(HomePageContainer)} exact path="/" />
<Route
path="/companies/:companyId/details"
render={(props: RouteComponentProps<{ companyId: string }>) => (
<CompanyDetailContainer {...props} fetchCompanyNew={fetchCompanyNew} httpRequest={Request} useFetchCompany={useFetchCompany} />
)}
/>
<Route component={withTracker(InterviewContainer)} path="/interviews/companies/:companyId" />
<Route component={withTracker(About)} path="/about" />
<Route component={withTracker(Container)} path="/" />
<Route component={withTracker(NotFound)} path="*" />
</Switch>
Here is how the company Link is coded:
Note: I am using Redux State
"react-redux": "^7.2.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
InterviewContainer.tsx (the parent that does the company fetching)
class InterviewContainer extends Component<PropsFromRedux & RouteComponentProps<{ companyId: string }>> {
componentDidMount() {
const { fetchCompany } = this.props;
const { companyId } = this.props.match.params;
fetchCompany(companyId);
}
render() {
const { company } = this.props;
return (company && <Interview className="ft-interview" company={company} />) || null;
}
}
const mapState = (state: RootState) => ({
company: state.company.company,
});
const mapDispatch = {
fetchCompany: fetchCompanyFromJSON,
};
const connector = connect(mapState, mapDispatch);
type PropsFromRedux = ConnectedProps<typeof connector>;
export default withRouter(connect(mapState, mapDispatch)(InterviewContainer));
LinkItem.tsx (one of the children rendered by InterviewContainer and receives the company from InterviewContainer)
render() {
const { company } = this.props,
uri = company.notInterviewed ? `companies/${company.id}/details` : `/interviews/companies/${company.id}`,
className = `margin-top-10 margin-bottom-10 ${company.notInterviewed ? 'ft-company-not-interviewed' : ''}`;
const link = (
<Link className={className} id={company.id.toString()} to={uri}>
<span id="company-name">{company.name}</span>
</Link>
);
}
I think I may have to reset Redux state on route change. I see people in the past have used LOCATION_CHANGE but that's outdated and that's a constant provided by third party redux libs that are no longer supported. So not sure how to do that with Redux v7+
So I think I just need a way to detect a location change and then somehow update my react store to reset company (set company: state.company.company, to undefined from my redux action)
I know things like this can be cumbersome. Have you tried passing in state with the Link as <Link to={uri} state={...someState} />. Then wherever it is loading it should rerender or reset props according to that. Maybe throw some skeleton loaders or conditional rendering logic.
I'm thoroughly lost and would like to ask for a recomendation on how to implement browser history inside my app.
With Router, all i have is a single component which gets assigned pages based on which page i'm on. pages and text inside app is acquired from an api, and whenever i click a button, the api gets called again.
<Router>
<Switch>
<Route to="/" component={Body} />
...
which probably doesnt even work as it should, because the Link tags are on the buttons, and they point to /page/number:
const renderPageNumbers = apiPagingSliced.map((links, index) => {
return <Link key={index} to={`/page/${links.label}`}>
<button key={index} id={links.label}
onClick={props.handleClick}
className={(links.active ? "mark-page" : "") + " " + (links.url === null ? "remove-btn" : "")}
>{links.label}
</button></Link>
}
)
i've managed to get it working so that i get "www.webpage.com/page/3" for example. But when i press back in browser, it only changes the url into previous page, doesn't do anything else. How do i implement a functional back/forward history function?
First you should add the route params example : "/:id"
<Route to="/some_page/:id" component={SomePage} />
Then import useHistory and UseParams from react-router :
import { useHistory, useParams } from "react-router-dom";
let { id } = useParams();
let history = useHistory();
<button onClick={() => history.push(`/some_page/${id}`)}> Go to page </button>
First you should add a route to the /page/(some number)
And this is done like this:
<Router>
<Switch>
<Route to="/" component={Body} />
<Route to="/page/:id" component={Page} />
...
And now in the Page component import a react router dom hook called useParams
import { useHistory } from 'react-router-dom'
const Page = () => {
const history = useHistory()
//pageID will be equal to the page number
return (
<div>
<button onClick={event => history.goBack`}>Go back!</button>
</div>
)
}
Test Case
https://codesandbox.io/s/rr00y9w2wm
Steps to reproduce
Click on Topics
Click on Rendering with React
OR
Go to https://rr00y9w2wm.codesandbox.io/topics/rendering
Expected Behavior
match.params.topicId should be identical from both the parent Topics component should be the same as match.params.topicId when accessed within the Topic component
Actual Behavior
match.params.topicId when accessed within the Topic component is undefined
match.params.topicId when accessed within the Topics component is rendering
I understand from this closed issue that this is not necessarily a bug.
This requirement is super common among users who want to create a run in the mill web application where a component Topics at a parent level needs to access the match.params.paramId where paramId is a URL param that matches a nested (child) component Topic:
const Topic = ({ match }) => (
<div>
<h2>Topic ID param from Topic Components</h2>
<h3>{match.params.topicId}</h3>
</div>
);
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<h3>{match.params.topicId || "undefined"}</h3>
<Route path={`${match.url}/:topicId`} component={Topic} />
...
</div>
);
In a generic sense, Topics could be a Drawer or Navigation Menu component and Topic could be any child component, like it is in the application I'm developing. The child component has it's own :topicId param which has it's own (let's say) <Route path="sections/:sectionId" component={Section} /> Route/Component.
Even more painful, the Navigation Menu needn't have a one-to-one relationship with the component tree. Sometimes the items at the root level of the menu (say Topics, Sections etc.) might correspond to a nested structure (Sections is only rendered under a Topic, /topics/:topicId/sections/:sectionId though it has its own normalized list that is available to the user under the title Sections in the Navigation Bar).
Therefore, when Sections is clicked, it should be highlighted, and not both Sections and Topics.
With the sectionId or sections path unavailable to the Navigation Bar component which is at the Root level of the application, it becomes necessary to write hacks like this for such a commonplace use case.
I am not an expert at all at React Router, so if anyone can venture a proper elegant solution to this use case, I would consider this to be a fruitful endeavor. And by elegant, I mean
Uses match and not history.location.pathname
Does not involve hacky approaches like manually parsing the window.location.xxx
Doesn't use this.props.location.pathname
Does not use third party libraries like path-to-regexp
Does not use query params
Other hacks/partial solutions/related questions:
React Router v4 - How to get current route?
React Router v4 global no match to nested route childs
TIA!
React-router doesn't give you the match params of any of the matched children Route , rather it gives you the params based on the current match. So if you have your Routes setup like
<Route path='/topic' component={Topics} />
and in Topics component you have a Route like
<Route path=`${match.url}/:topicId` component={Topic} />
Now if your url is /topic/topic1 which matched the inner Route but for the Topics component, the matched Route is still, /topic and hence has no params in it, which makes sense.
If you want to fetch params of the children Route matched in the topics component, you would need to make use of matchPath utility provided by React-router and test against the child route whose params you want to obtain
import { matchPath } from 'react-router'
render(){
const {users, flags, location } = this.props;
const match = matchPath(location.pathname, {
path: '/topic/:topicId',
exact: true,
strict: false
})
if(match) {
console.log(match.params.topicId);
}
return (
<div>
<Route exact path="/topic/:topicId" component={Topic} />
</div>
)
}
EDIT:
One method to get all the params at any level is to make use of context and update the params as and when they match in the context Provider.
You would need to create a wrapper around Route for it to work correctly, A typical example would look like
RouteWrapper.jsx
import React from "react";
import _ from "lodash";
import { matchPath } from "react-router-dom";
import { ParamContext } from "./ParamsContext";
import { withRouter, Route } from "react-router-dom";
class CustomRoute extends React.Component {
getMatchParams = props => {
const { location, path, exact, strict } = props || this.props;
const match = matchPath(location.pathname, {
path,
exact,
strict
});
if (match) {
console.log(match.params);
return match.params;
}
return {};
};
componentDidMount() {
const { updateParams } = this.props;
updateParams(this.getMatchParams());
}
componentDidUpdate(prevProps) {
const { updateParams, match } = this.props;
const currentParams = this.getMatchParams();
const prevParams = this.getMatchParams(prevProps);
if (!_.isEqual(currentParams, prevParams)) {
updateParams(match.params);
}
}
componentWillUnmount() {
const { updateParams } = this.props;
const matchParams = this.getMatchParams();
Object.keys(matchParams).forEach(k => (matchParams[k] = undefined));
updateParams(matchParams);
}
render() {
return <Route {...this.props} />;
}
}
const RouteWithRouter = withRouter(CustomRoute);
export default props => (
<ParamContext.Consumer>
{({ updateParams }) => {
return <RouteWithRouter updateParams={updateParams} {...props} />;
}}
</ParamContext.Consumer>
);
ParamsProvider.jsx
import React from "react";
import { ParamContext } from "./ParamsContext";
export default class ParamsProvider extends React.Component {
state = {
allParams: {}
};
updateParams = params => {
console.log({ params: JSON.stringify(params) });
this.setState(prevProps => ({
allParams: {
...prevProps.allParams,
...params
}
}));
};
render() {
return (
<ParamContext.Provider
value={{
allParams: this.state.allParams,
updateParams: this.updateParams
}}
>
{this.props.children}
</ParamContext.Provider>
);
}
}
Index.js
ReactDOM.render(
<BrowserRouter>
<ParamsProvider>
<App />
</ParamsProvider>
</BrowserRouter>,
document.getElementById("root")
);
Working DEMO
Try utilizing query parameters ? to allow the parent and child to access the current selected topic. Unfortunately, you will need to use the module qs because react-router-dom doesn't automatically parse queries (react-router v3 does).
Working example: https://codesandbox.io/s/my1ljx40r9
URL is structured like a concatenated string:
topic?topic=props-v-state
Then you would add to the query with &:
/topics/topic?topic=optimization&category=pure-components&subcategory=shouldComponentUpdate
✔ Uses match for Route URL handling
✔ Doesn't use this.props.location.pathname (uses this.props.location.search)
✔ Uses qs to parse location.search
✔ Does not involve hacky approaches
Topics.js
import React from "react";
import { Link, Route } from "react-router-dom";
import qs from "qs";
import Topic from "./Topic";
export default ({ match, location }) => {
const { topic } = qs.parse(location.search, {
ignoreQueryPrefix: true
});
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/topic?topic=rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/topic?topic=components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/topic?topic=props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<h2>
Topic ID param from Topic<strong>s</strong> Components
</h2>
<h3>{topic && topic}</h3>
<Route
path={`${match.url}/:topicId`}
render={props => <Topic {...props} topic={topic} />}
/>
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
};
Another approach would be to create a HOC that stores params to state and children update the parent's state when its params have changed.
URL is structured like a folder tree: /topics/rendering/optimization/pure-components/shouldComponentUpdate
Working example: https://codesandbox.io/s/9joknpm9jy
✔ Uses match for Route URL handling
✔ Doesn't use this.props.location.pathname
✔ Uses lodash for object to object comparison
✔ Does not involve hacky approaches
Topics.js
import map from "lodash/map";
import React, { Fragment, Component } from "react";
import NestedRoutes from "./NestedRoutes";
import Links from "./Links";
import createPath from "./createPath";
export default class Topics extends Component {
state = {
params: "",
paths: []
};
componentDidMount = () => {
const urlPaths = [
this.props.match.url,
":topicId",
":subcategory",
":item",
":lifecycles"
];
this.setState({ paths: createPath(urlPaths) });
};
handleUrlChange = params => this.setState({ params });
showParams = params =>
!params
? null
: map(params, name => <Fragment key={name}>{name} </Fragment>);
render = () => (
<div>
<h2>Topics</h2>
<Links match={this.props.match} />
<h2>
Topic ID param from Topic<strong>s</strong> Components
</h2>
<h3>{this.state.params && this.showParams(this.state.params)}</h3>
<NestedRoutes
handleUrlChange={this.handleUrlChange}
match={this.props.match}
paths={this.state.paths}
showParams={this.showParams}
/>
</div>
);
}
NestedRoutes.js
import map from "lodash/map";
import React, { Fragment } from "react";
import { Route } from "react-router-dom";
import Topic from "./Topic";
export default ({ handleUrlChange, match, paths, showParams }) => (
<Fragment>
{map(paths, path => (
<Route
exact
key={path}
path={path}
render={props => (
<Topic
{...props}
handleUrlChange={handleUrlChange}
showParams={showParams}
/>
)}
/>
))}
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</Fragment>
);
If you have a known set of child routes then you can use something like this:
Import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'
<Router>
<Route path={`${baseUrl}/home/:expectedTag?/:expectedEvent?`} component={Parent} />
</Router>
const Parent = (props) => {
return (
<div >
<Switch>
<Route path={`${baseUrl}/home/summary`} component={ChildOne} />
<Route
path={`${baseUrl}/home/:activeTag/:activeEvent?/:activeIndex?`}
component={ChildTwo}
/>
</Switch>
<div>
)
}
In the above example Parent will get expectedTag, expectedEvent as the match params and there is no conflict with the child components and Child component will get activeTag, activeEvent, activeIndex as the parameters. Same name for params can also be used, I have tried that as well.
Try to do something like this:
<Switch>
<Route path="/auth/login/:token" render={props => <Login {...this.props} {...props}/>}/>
<Route path="/auth/login" component={Login}/>
First, the route with the parameter and after the link without parameter.
Inside my Login component I put this line of code console.log(props.match.params.token); to test and worked for me.
If you happen to use React.FC, there is a hook useRouteMatch.
For instance, parent component routes:
<div className="office-wrapper">
<div className="some-parent-stuff">
...
</div>
<div className="child-routes-wrapper">
<Switch>
<Route exact path={`/office`} component={List} />
<Route exact path={`/office/:id`} component={Alter} />
</Switch>
</div>
</div>
And in your child component:
...
import { useRouteMatch } from "react-router-dom"
...
export const Alter = (props) => {
const match = useRouteMatch()
const officeId = +match.params.id
//... rest function code
}
I am trying to implement React Router Breadcrumbs for v4
Following are my routes:
const routes = {
'/': 'Home',
'/page1': 'Page 1',
'/page2': 'Page 2'
};
I could put the breadcrumbs using this library in my application, however I am having following questions:
Que. #1:
When I click on Home in my breadcrumbs, I can see the URL changes to http://localhost:8080 However, browser still shows the same page I am on.
Que. #2:
When I navigate to Page2 from Page1, url changes from http://localhost:8080/page1 to http://localhost:8080/page2.
So the breadcrumbs shown changes to Home / Page 2 instead of changing like Home / Page 1 / Page 2
I know this may be because the url just has /page2 after hostname. But, can I achieve the display like: Home / Page 1 / Page 2?
Below is the code in my main App.jsx:
<Router>
<div>
<Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
<Route exact path="/" component={LandingPage}/>
<Route path="/page1" component={Page1}/>
<Route path="/page2" component={Page2}/>
</div>
</Router>
and if I use like belowto cater for breadcrumbs, then my page2 gets rendered below page1 stuff:
<Router>
<div>
<Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
<Route exact path="/" component={LandingPage}/>
<Route path="/page1" component={Page1}/>
<Route path="/page1/page2" component={Page2}/>
</div>
</Router>
Answer:
Que. #1: No need to wrap <Breadcrumbs ..../> element inside <Router> element inside each Component of application. This may be because, inclusion of <Router> element inside each Component leads to "nesting" of Router elements (note we have Router tag in landing page as well); which does not work with react router v4.
Que. #2: Refer to answer formally marked here (answered by palsrealm below)
Your breadcrumbs are based on links and they work as designed. To display the pages, you need to set up a Switch with Routes in it which would load the appropriate components when the path changes. Something like
<Switch>
<Route path='/' component={Home}/>
<Route path='/page1' component={Page1}/>
<Route path='/page2' component={Page2}/>
</Switch>
If you want the breadcrumb to show Home/Page1/Page2 your routes should be '/page1/page2' : 'Page 2'. The Route should also change accordingly.
Edit: Your Router should be
<Router>
<div>
<Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
<Switch>
<Route exact path="/" component={LandingPage}/>
<Route exact path="/page1" component={Page1}/>
<Route path="/page1/page2" component={Page2}/>
</Switch>
</div>
</Router>
This can also be accomplished with a HOC which would allow you to use a route config object to set breadcrumbs instead. I've open-sourced it here, but the source code is below as well:
Breadcrumbs.jsx
import React from 'react';
import { NavLink } from 'react-router-dom';
import { withBreadcrumbs } from 'withBreadcrumbs';
const UserBreadcrumb = ({ match }) =>
<span>{match.params.userId}</span>; // use match param userId to fetch/display user name
const routes = [
{ path: 'users', breadcrumb: 'Users' },
{ path: 'users/:userId', breadcrumb: UserBreadcrumb},
{ path: 'something-else', breadcrumb: ':)' },
];
const Breadcrumbs = ({ breadcrumbs }) => (
<div>
{breadcrumbs.map(({ breadcrumb, path, match }) => (
<span key={path}>
<NavLink to={match.url}>
{breadcrumb}
</NavLink>
<span>/</span>
</span>
))}
</div>
);
export default withBreadcrumbs(routes)(Breadcrumbs);
withBreadcrumbs.js
import React from 'react';
import { matchPath, withRouter } from 'react-router';
const renderer = ({ breadcrumb, match }) => {
if (typeof breadcrumb === 'function') { return breadcrumb({ match }); }
return breadcrumb;
};
export const getBreadcrumbs = ({ routes, pathname }) => {
const matches = [];
pathname
.replace(/\/$/, '')
.split('/')
.reduce((previous, current) => {
const pathSection = `${previous}/${current}`;
let breadcrumbMatch;
routes.some(({ breadcrumb, path }) => {
const match = matchPath(pathSection, { exact: true, path });
if (match) {
breadcrumbMatch = {
breadcrumb: renderer({ breadcrumb, match }),
path,
match,
};
return true;
}
return false;
});
if (breadcrumbMatch) {
matches.push(breadcrumbMatch);
}
return pathSection;
});
return matches;
};
export const withBreadcrumbs = routes => Component => withRouter(props => (
<Component
{...props}
breadcrumbs={
getBreadcrumbs({
pathname: props.location.pathname,
routes,
})
}
/>
));
The following component should return a breadcrumb at any depth, except on the home page (for obvious reasons). You won't need React Router Breadcrumb. My first public contribution, so if I'm missing an essential part, it would be great if somebody could point it out. I added » for crumbs splits, but you can obviously update that to match what you need.
import React from 'react'
import ReactDOM from 'react-dom'
import { Route, Link } from 'react-router-dom'
// styles
require('./styles/_breadcrumbs.scss')
// replace underscores with spaces in path names
const formatLeafName = leaf => leaf.replace('_', ' ')
// create a path based on the leaf position in the branch
const formatPath = (branch, index) => branch.slice(0, index + 1).join('/')
// output the individual breadcrumb links
const BreadCrumb = props => {
const { leaf, index, branch } = props,
leafPath = formatPath(branch, index),
leafName = index == 0 ? 'home' : formatLeafName(leaf),
leafItem =
index + 1 < branch.length
? <li className="breadcrumbs__crumb">
<Link to={leafPath}>{leafName}</Link>
<span className="separator">»</span>
</li>
: <li className="breadcrumbs__crumb">{leafName}</li>
// the slug doesn't need a link or a separator, so we output just the leaf name
return leafItem
}
const BreadCrumbList = props => {
const path = props.match.url,
listItems =
// make sure we're not home (home return '/' on url)
path.length > 1
&& path
// create an array of leaf names
.split('/')
// send our new array to BreadCrumb for formating
.map((leaf, index, branch) =>
<BreadCrumb leaf={leaf} index={index} branch={branch} key={index} />
)
// listItem will exist anywhere but home
return listItems && <ul className="breadcrumbs">{listItems}</ul>
}
const BreadCrumbs = props =>
<Route path="/*" render={({ match }) => <BreadCrumbList match={match} />} />
export default BreadCrumbs
I am using react with react-router.
I am trying to pass property’s in a "Link" of react-router
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');
var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
render : function(){
return(
<div>
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="ideas" handler={CreateIdeaView} />
<DefaultRoute handler={Home} />
</Route>
);
Router.run(routes, function(Handler) {
React.render(<Handler />, document.getElementById('main'))
});
The "Link" renders the page but does not pass the property to the new view.
Below is the view code
var React = require('react');
var Router = require('react-router');
var CreateIdeaView = React.createClass({
render : function(){
console.log('props form link',this.props,this)//props not recived
return(
<div>
<h1>Create Post: </h1>
<input type='text' ref='newIdeaTitle' placeholder='title'></input>
<input type='text' ref='newIdeaBody' placeholder='body'></input>
</div>
);
}
});
module.exports = CreateIdeaView;
How can I pass data using "Link"?
This line is missing path:
<Route name="ideas" handler={CreateIdeaView} />
Should be:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
Given the following Link (outdated v1):
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
Up to date as of v4/v5:
const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
// Using query
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />
// Using search
<Link to={{pathname: `/${this.props.testvalue}`, search: `?backUrl=${backUrl}`} />
<Link to={`/${this.props.testvalue}?backUrl=${backUrl}`} />
and in the withRouter(CreateIdeaView) components render(), out dated usage of withRouter higher order component:
console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value
And in a functional components using the useParams and useLocation hooks:
const CreatedIdeaView = () => {
const { testvalue } = useParams();
const { query, search } = useLocation();
console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl'))
return <span>{testvalue} {backurl}</span>
}
From the link that you posted on the docs, towards the bottom of the page:
Given a route like <Route name="user" path="/users/:userId"/>
Updated code example with some stubbed query examples:
// import React, {Component, Props, ReactDOM} from 'react';
// import {Route, Switch} from 'react-router'; etc etc
// this snippet has it all attached to window since its in browser
const {
BrowserRouter,
Switch,
Route,
Link,
NavLink
} = ReactRouterDOM;
class World extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromIdeas: props.match.params.WORLD || 'unknown'
}
}
render() {
const { match, location} = this.props;
return (
<React.Fragment>
<h2>{this.state.fromIdeas}</h2>
<span>thing:
{location.query
&& location.query.thing}
</span><br/>
<span>another1:
{location.query
&& location.query.another1
|| 'none for 2 or 3'}
</span>
</React.Fragment>
);
}
}
class Ideas extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromAppItem: props.location.item,
fromAppId: props.location.id,
nextPage: 'world1',
showWorld2: false
}
}
render() {
return (
<React.Fragment>
<li>item: {this.state.fromAppItem.okay}</li>
<li>id: {this.state.fromAppId}</li>
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'asdf', another1: 'stuff'}
}}>
Home 1
</Link>
</li>
<li>
<button
onClick={() => this.setState({
nextPage: 'world2',
showWorld2: true})}>
switch 2
</button>
</li>
{this.state.showWorld2
&&
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'fdsa'}}} >
Home 2
</Link>
</li>
}
<NavLink to="/hello">Home 3</NavLink>
</React.Fragment>
);
}
}
class App extends React.Component {
render() {
return (
<React.Fragment>
<Link to={{
pathname:'/ideas/:id',
id: 222,
item: {
okay: 123
}}}>Ideas</Link>
<Switch>
<Route exact path='/ideas/:id/' component={Ideas}/>
<Route path='/hello/:WORLD?/:thing?' component={World}/>
</Switch>
</React.Fragment>
);
}
}
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('ideas'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"></script>
<div id="ideas"></div>
#updates:
See: https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors
From the upgrade guide from 1.x to 2.x:
<Link to>, onEnter, and isActive use location descriptors
<Link to> can now take a location descriptor in addition to strings.
The query and state props are deprecated.
// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>
// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>
// Still valid in 2.x
<Link to="/foo"/>
Likewise, redirecting from an onEnter hook now also uses a location
descriptor.
// v1.0.x
(nextState, replaceState) => replaceState(null, '/foo')
(nextState, replaceState) => replaceState(null, '/foo', { the: 'query' })
// v2.0.0
(nextState, replace) => replace('/foo')
(nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } })
For custom link-like components, the same applies for router.isActive,
previously history.isActive.
// v1.0.x
history.isActive(pathname, query, indexOnly)
// v2.0.0
router.isActive({ pathname, query }, indexOnly)
#updates for v3 to v4:
https://github.com/ReactTraining/react-router/blob/432dc9cf2344c772ab9f6379998aa7d74c1d43de/packages/react-router/docs/guides/migrating.md
https://github.com/ReactTraining/react-router/pull/3803
https://github.com/ReactTraining/react-router/pull/3669
https://github.com/ReactTraining/react-router/pull/3430
https://github.com/ReactTraining/react-router/pull/3443
https://github.com/ReactTraining/react-router/pull/3803
https://github.com/ReactTraining/react-router/pull/3636
https://github.com/ReactTraining/react-router/pull/3397
https://github.com/ReactTraining/react-router/pull/3288
The interface is basically still the same as v2, best to look at the CHANGES.md for react-router, as that is where the updates are.
"legacy migration documentation" for posterity
https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md
https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md
https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md
https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md
https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md
https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md
there is a way you can pass more than one parameter. You can pass "to" as object instead of string.
// your route setup
<Route path="/category/:catId" component={Category} / >
// your link creation
const newTo = {
pathname: "/category/595212758daa6810cbba4104",
param1: "Par1"
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>
// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104
this.props.location.param1 // this is Par1
I had the same problem to show an user detail from my application.
You can do this:
<Link to={'/ideas/'+this.props.testvalue }>Create Idea</Link>
or
<Link to="ideas/hello">Create Idea</Link>
and
<Route name="ideas/:value" handler={CreateIdeaView} />
to get this via this.props.match.params.value at your CreateIdeaView class.
You can see this video that helped me a lot: https://www.youtube.com/watch?v=ZBxMljq9GSE
See this post for reference
The simple is that:
<Link to={{
pathname: `your/location`,
state: {send anything from here}
}}
Now you want to access it:
this.props.location.state
as for react-router-dom 4.x.x (https://www.npmjs.com/package/react-router-dom) you can pass params to the component to route to via:
<Route path="/ideas/:value" component ={CreateIdeaView} />
linking via (considering testValue prop is passed to the corresponding component (e.g. the above App component) rendering the link)
<Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
passing props to your component constructor the value param will be available via
props.match.params.value
After install react-router-dom
<Link
to={{
pathname: "/product-detail",
productdetailProps: {
productdetail: "I M passed From Props"
}
}}>
Click To Pass Props
</Link>
and other end where the route is redirected do this
componentDidMount() {
console.log("product props is", this.props.location.productdetailProps);
}
Inside your Link component do the state
<Link to='register' state={{name:'zayne'}}>
Now to access the item in the page you went to, import useLocation
import {useLocation} from 'react-router-dom';
const Register=()=>{
const location = useLocation()
//store the state in a variable if you want
//location.state then the property or object you want
const Name = location.state.name
return(
<div>
hello my name is {Name}
</div>
)
}
Typescript
For approach mentioned like this in many answers,
<Link
to={{
pathname: "/my-path",
myProps: {
hello: "Hello World"
}
}}>
Press Me
</Link>
I was getting error,
Object literal may only specify known properties, and 'myProps' does not exist in type 'LocationDescriptorObject | ((location: Location) => LocationDescriptor)'
Then I checked in the official documentation they have provided state for the same purpose.
So it worked like this,
<Link
to={{
pathname: "/my-path",
state: {
hello: "Hello World"
}
}}>
Press Me
</Link>
And in your next component you can get this value as following,
componentDidMount() {
console.log("received "+this.props.location.state.hello);
}
To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
For v5
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
React Router Official Site
For v6: Attention! state should be outside from to={}
// route setup
<Route path="/employee-edit/:empId" element={<EmployeeEdit />} / >
Link to Component
<Link to={"/employee-edit/1"} state={{ data: employee }} > Edit </Link>
or
<Link to={{
pathname: "/employee-edit/1",
search: "?sort=name",
hash: "#the-hash",
}}
state={{ data: employee }} > Edit </Link>
Note: state is outside from to{}, but for
v5:
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
Funtional component:
import React from "react";
import { useLocation } from "react-router-dom";
const LinkTest = () => {
const location = useLocation();
console.log("Location", location);
return <h1>Link Test</h1>;
};
export default LinkTest;
Class Component: in order to work with hooks, we need to wrap it in functional component and pass props:
import React, { Component } from "react";
import { useLocation, useParams } from "react-router-dom";
class LinkTestComponent extends Component {
render() {
console.log(this.props);
return <h1>Link Test</h1>;
}
}
export default () => (
<LinkTestComponent params={useParams()} location={useLocation()} />
);
Tested with: "react-router-dom": "^6.2.2",
In my case I had a function component with empty props and this solved it:
<Link
to={{
pathname: `/dashboard/${device.device_id}`,
state: { device },
}}
>
View Dashboard
</Link>
In your function component you should have something like this:
import { useLocation } from "react-router"
export default function Dashboard() {
const location = useLocation()
console.log(location.state)
return <h1>{`Hello, I'm device ${location.state.device.device_id}!`}</h1>
}
The simplest approach would be to make use of the to:object within link as mentioned in documentation:
https://reactrouter.com/web/api/Link/to-object
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true, id: 1 }
}}
/>
We can retrieve above params (state) as below:
this.props.location.state // { fromDashboard: true ,id: 1 }
If you are just looking to replace the slugs in your routes, you can use generatePath that was introduced in react-router 4.3 (2018). As of today, it isn't included in the react-router-dom (web) documentation, but is in react-router (core). Issue#7679
// myRoutes.js
export const ROUTES = {
userDetails: "/user/:id",
}
// MyRouter.jsx
import ROUTES from './routes'
<Route path={ROUTES.userDetails} ... />
// MyComponent.jsx
import { generatePath } from 'react-router-dom'
import ROUTES from './routes'
<Link to={generatePath(ROUTES.userDetails, { id: 1 })}>ClickyClick</Link>
It's the same concept that django.urls.reverse has had for a while.
I was struggling with this for a few hours and not a single answer in this topic worked for me. Finally I managed to find a solution for React Router 6 in the documentation.
Here is full example:
// App.js
<BrowserRouter>
<Routes>
<Route path="/books/:bookId" element={ <BookDetails /> } />
</Routes>
</BrowserRouter>
// BookDetails.js
import React from "react"
import { useParams } from "react-router-dom"
export default function BookPage() {
const params = useParams()
return <div> { console.log(params.bookId) } </div>
}
Note that useParams cannot be called inside a class component so you must use function component (see this answer for details).
In react-router v6 it is with state and useLocation:
<Link to={`/foo`} state={{title: 'foo'}}>
import {useLocation} from "react-router-dom";
const FooPage = () => {
const location = useLocation()
return <>
<h1>{location.state.title}</h1>
</>
}
export default FooPage;
Route:
<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />
And then can access params in your PageCustomer component like this: this.props.match.params.id.
For example an api call in PageCustomer component:
axios({
method: 'get',
url: '/api/customers/' + this.props.match.params.id,
data: {},
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
Updating 25-11-21
Thanks for alex-adestech.mx who wrote above.
I was able to transfer the whole object and pull out all the necessary fields from it
in send-component :
<Button type="submit" component={NavLink} to={{
pathname: '/basequestion',
state: {question} }}
variant="contained"
size="small">Take test</Button>
in receive-component:
import { useLocation } from "react-router"
const BaseQuestion = () => {
const location = useLocation();
const {description, title, images} = (location.state.question);