score:117
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
score:0
try this.
<Route exact path="/details/:id" render={(props)=>{return(
<DetailsPage id={props.match.params.id}/>)
}} />
In details page try this...
this.props.id
score:0
Simple example with Class, HoC and Router v5
package.json
"react-router-dom": "5.3.1",
"react-router": "5.3.1",
"@types/react-router-dom": "5.3.3",
// YourComponent.tsx
import React from 'react';
import { RouteComponentProps, withRouter } from 'react-router';
export interface PathParams {
id: string;
}
export interface Props extends RouteComponentProps<PathParams> {}
export interface State {}
class YourComponent extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {};
console.log(props.match.params) // { id: 1 }
// TypeScript completions
console.log(props.match.params.id) // 1
}
render() {
return <></>;
}
}
export default withRouter(YourComponent);
// App.tsx
import './App.css';
import React from 'react';
import { Route, Switch, Router } from 'react-router-dom';
import YourComponent from './YourComponent';
function App(): JSX.Element {
return (
<Router>
<Switch>
<Route
path="/details/:id"
component={() => <YourComponent />}
/>
</Switch>
</Router>
);
}
export default App;
score:2
if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route>
props to your target component:
exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}
score:3
This is for react-router-dom v6 (I highly suggest using functional components for this)
It's somewhat painful for react-router-dom to keep changing syntax and rules. But here goes nothing.
You can use both useParams
and useSelector
to solve this
import { useParams } from 'react-router';
import { useSelector } from 'react-redux';
const Component = () => {
const { id } = useParams(); //returns the :id
const page = useSelector((state) => state.something[id]); //returns state of the page
return <div>Page Detail</div>;
}
export default Component;
BUT, the problem persist when you also have an action creator and you want to pass it as a props in connect
function
export const connect(mapStateToProps, mapDispatchToProps)(Component)
since we are using useParams
, it won't be passed to mapStateToProps
that we created
const mapStateToProps = (state, ownProps) => {
console.log(ownProps) //wont recognize :id
//hence
return {
someReducers: state.someReducers[id] //would return an error: 'id' is not defined
};
};
on the other hand, you can't entirely ignore the connect
function since you need mapDispatchToProps
to work with your component.
The workaround to this is to create a Higher Order Component withRouter
function yourself. This was a deprecated react-router-dom helper.
//make this
import { useParams, useLocation, useNavigate } from 'react-router';
import { connect } from 'react-redux';
import { yourActionCreator } from '../actionCreator';
const withRouter = (Child) => {
return (props) => {
const location = useLocation();
const navigation = useNavigate();
const params = useParams();
return (
<Child
{...props}
params={params}
navigate={navigate}
location={location}
/>
);
};
};
const Component = () => {
// your component...
return <div> Page Detail </div>
};
export mapStateToProps = (state, ownProps) => {
console.log(ownProps) // would contain the :id params
return {
//something
}
};
const mapDispatchToProps = {
yourActionCreator
}
export withRouter(connect(mapStateToProps, mapDispatchToProps)(Component));
score:4
Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to
property of the <Link />
component. The search parameters can later be accessed via new URLSearchParams()
;
<Link
key={id}
to={{
pathname: this.props.match.url + '/' + foo,
search: '?foo=' + foo
}} />
<Route path="/details/:foo" component={DetailsPage}/>
export default class DetailsPage extends Component {
state = {
foo: ''
}
componentDidMount () {
this.parseQueryParams();
}
componentDidUpdate() {
this.parseQueryParams();
}
parseQueryParams () {
const query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
if (this.state.foo!== param[1]) {
this.setState({foo: param[1]});
}
}
}
render() {
return(
<div>
<h2>{this.state.foo}</h2>
</div>
)
}
}
score:5
Here's typescript version. works on "react-router-dom": "^4.3.1"
export const AppRouter: React.StatelessComponent = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
<Route path="/" exact component={App} />
</Switch>
</BrowserRouter>
);
};
and component
export class ProblemPage extends React.Component<ProblemRouteTokens> {
public render(): JSX.Element {
return <div>{this.props.problemId}</div>;
}
}
where ProblemRouteTokens
export interface ProblemRouteTokens { problemId: string; }
score:12
Use the component:
<Route exact path="/details/:id" component={DetailsPage} />
And you should be able to access the id
using:
this.props.match.params.id
Inside the DetailsPage
component
score:14
In addition to Alexander Lunas answer ... If you want to add more than one argument just use:
<Route path="/details/:id/:title" component={DetailsPage}/>
export default class DetailsPage extends Component {
render() {
return(
<div>
<h2>{this.props.match.params.id}</h2>
<h3>{this.props.match.params.title}</h3>
</div>
)
}
}
score:40
Use render method:
<Route exact path="/details/:id" render={(props) => (
<DetailsPage id={props.match.params.id}/>
)} />
And you should be able to access the id using:
this.props.id
Inside the DetailsPage component
score:60
Since react-router v5.1 with hooks:
import { useParams } from 'react-router';
export default function DetailsPage() {
const { id } = useParams();
}
score:134
I used this to access the ID in my component:
<Route path="/details/:id" component={DetailsPage}/>
And in the detail component:
export default class DetailsPage extends Component {
render() {
return(
<div>
<h2>{this.props.match.params.id}</h2>
</div>
)
}
}
This will render any ID inside an h2, hope that helps someone.
Source: stackoverflow.com
Related Query
- React Router Pass Param to Component
- How to pass the match when using render in Route component from react router (v4)
- pass "key" param to react component
- ReactJS: Pass parameter from rails to react router to component
- React router pass props to route component
- React router - pass api data to the linked component to open with a new page
- I can not get the state from react router Link component using useLocation. So how can I pass it?
- How to pass a wrapped component into React Router without it constantly remounting
- React router dom passing data from parent component to child router component does not pass the props.match
- React Router 4 Pass props to dynamic component
- How to pass id in path url as component property in react router v6
- React router pass callback with current route to child component
- Pass object into react component using react router
- React Router - Pass chosen component to parent
- React Pass history to a component defined in the Router
- Pass useState state to router component in React
- How to access param in parent component with React Router DOM
- React Router Dom, pass data to a component with useNavigate
- How to pass a prop from one component to another when using react router link
- React Router v4 Nested Routes pass in match with Class Component
- How to pass data to another component not in the URL with React Router
- How can I pass props from one component to another using Link and router in react
- how to get route param values of child component from parent component in app using React Router
- How to pass context consumer to Component (Event.js) rendered by React Router only?
- Pass store to the layout component in react router redux?
- Pass path Param to render() function of Route in Switch - React Router
- How to pass prop to react router component via NavDropdown.Item link
- Pass prop through react router to component
- React Router pass props to component rendered by <Link />?
- React Router 4: Pass route props to layout component
More Query from same tag
- How to add data from Laravel using a ReactJs component?
- How to stack elements (cards) horizontally in a row within a parent element (div)
- Why when I login with the empty shopping cart it gives me an error with .map?
- React Render Map last element doesnt update
- how to handle lazy import in functional component react js avoid import befor need to render
- Ignore or prevent ESLint errors from breaking the build in React webpack project
- Received a promise that resolves to: undefined. Promise elements must resolve to a class or function
- webpack production build bundle.js file size is 10mb
- Not changing values of form reactjs
- @loadable/componet not loading on server side rendering
- Cannot access pxToRem function in Material-ui for theme
- How to pass coordinates data from a class to another class in React
- Namespace 'React' has no exported member 'InputHTMLAttributes' and Interface 'MenuItemProps' incorrectly extends interface 'ListItemProps'
- Get the values in the form, from a component outside the form
- React fucntional component state issue
- Prevent to open dialog modal in loop
- Getting Invalid hook call error on importing a component in React
- How can I keep an image from overflowing its container?
- Table inside other table row in ReactJS
- How to add space in a code area using HTML CSS
- Cannot read property from component when separating out code
- Redux mapDispatchToProps access action within array.map
- How to show form validation error in react
- Uncaught SyntaxError: Unexpected token '<' when serving the react
- React add array to state array
- React-Native Button onPress not working
- Custom button in toolbar draftjs editor
- React Router Kepps css when switching Routes
- onclick event for Imported component in react?
- useState is not updating state immediately