score:4
Navigate programmatically
Send parameters to useNavigate
const navigate = useNavigate();
function _navigateToPage (pageNumber) {
const page = pageNumber
const title = "Hello World";
navigate("/fragment", {
state:{
page,
title
},
});
}
Retrieve parameters in other page with useLocation
const params = useLocation();
console.log(params);
score:8
I had this same problem and scoured the internet for an easy solution. I didn't want to rewrite all my class components as functional components but I thought I might have to. However, I used a withRouter function with useParams() and it works really well and is easy to follow.
To solve your problem so you don't have to rewrite your DetailsPage class as a function, follow these steps:
Add the following line of code at the beginning of your class:
import { useParams } from 'react-router-dom';
Then add this function above your class (copy it exactly):
export function withRouter(Children){ return(props)=>{ const match = {params: useParams()}; return <Children {...props} match = {match}/> } }
Next, change your class definition to this:
class DetailsPage extends React.Component {
Add the following line of code at the end of your class:
export default withRouter(DetailsPage);
score:17
Pass props via Link component in React Router v6 by a separate prop called state
like <Link to="/" state={{ foo: bar }}>
.
Example:
<Link
to={`/login`}
state={{ from: "the-page-id" }}
>
Login to see this page
</Link>
And retrieve it using useLocation()
hook:
import { useLocation } from "react-router-dom";
...
const location = useLocation();
const { from } = location.state;
console.log(from); // output: "the-page-id"
This should be used with function components only not class components.
score:19
Using react-router-dom v6
Parent component (App)
<Route path="/something/:id" element={<Something />} />
Child component (Something)
import { useParams } from "react-router-dom";
const Something = (props) => {
let { id } = useParams();
useEffect(() => {
console.log(`/something/${id}`);
}, []);
// .....
}
score:34
Issue(s)
- react-router-dom v6
Route
components rendered via theelement
prop don't receive route props. - Route children components must use react hooks to access the route context, i.e.
useParams
,useLocation
,useNavigate
, etc... and therefore must be function components. - There no longer exists a
withRouter
Higher Order Component.
Solution
DetailsPage
is a class-based component so I see a couple options for getting access to the route's match params.
- Convert
DetailsPage
to be a function component and use theuseParams
react hook. - Write your own
withRouter
HOC to access the route context and pass as props any of the react-hook accessible values.
I won't cover converting a class-based component to a function component, but can provide a simple HOC solution to pass to DetailsPage
(or any other class-based component) the match params.
const withRouter = WrappedComponent => props => {
const params = useParams();
// etc... other react-router-dom v6 hooks
return (
<WrappedComponent
{...props}
params={params}
// etc...
/>
);
};
You can now wrap & export your class-based components in the very familiar way they were from v4/v5.
Source: stackoverflow.com
Related Query
- How to pass params into link using React router v6?
- I can not get the state from react router Link component using useLocation. So how can I pass it?
- How to pass props using react router link v6?
- How to pass a prop from one component to another when using react router link
- How can I pass props from one component to another using Link and router in react
- How can I pass data using <Redirect> in react router v4?
- How to pass the match when using render in Route component from react router (v4)
- how to pass props to the route when using react router <Link>
- How do you pass data when using the navigate function in react router v6
- How to pass data from a page to another page using react router
- React router dom - Link. How can I put an ID into the path of Link
- how to get params using react router dom v5.0.1
- How to pass a wrapped component into React Router without it constantly remounting
- Pass object into react component using react router
- How to pass a variable with text and a link into a React element
- How to pass extra params with react router
- How can I pass Apollo data and React Router 4 url params to my components
- can't pass props using Link in react router dom
- How can I pass function using props in React Router Link?
- How to click a button and navigate to a new route with URL params using React Router 4
- How to explicitly pass router params to React Component?
- How do I pass Meteor Subscription Data into React Component Props using ES6
- How to reload a page using react router Link component?
- How do pass string into variable using the request api inside my react component?
- How to transfer data from one parent component to another parent component in react using router / router params
- How to link to certain page upon form submission using React Router
- How to use Context API to pass down a state while using a Router in React JS
- React couldn't pass a data from one class component into another using Link
- How to pass props inside of Router while using React Context
- How to pass props/params/state to a Route with Link in React Router 5.2.0?
More Query from same tag
- React-Warning-Keys with no List or .map
- Recipe gets posted but doesn't get saved
- access to redux form values
- Function is not defined no-undef
- Calculate new state by old state and result of a promise
- How to clear the component stored redux state in componentWillUnmount?
- useEffect is not always called with React Router
- How to define variable in class component
- React and Flux - how to tie view to store data
- Changing colorIndex of grommet components
- How to sort sum up all values from object arrays inside react props
- Does removing unused imports have an impact on bundle size and build time in Reactjs
- react-bootstrap Accordion not collapsing with map
- Can't trigger a search function for movie API project because useState is in a different component
- How can I get component's position by ref in React?
- TypeError: setState is not a function in React
- Export a function from another js file in React
- Seeking advice: Reason for maximum update depth exceed
- Cannot read property '_currentElement' of null
- Connected Component testing with certain prop (React/Redux)
- ReactJS: always transfer props to child component
- TypeError: this.props.decrementCount is not a function
- Cannot read property 'error' of undefined. What's the problem?
- CreatedAt in MongoDB can“t be sorted
- React Typescript mapping with an existing object
- React+Typescript conditional rendering
- Typescript: How to dynamically add a method to a function with autocompletion?
- Styling in Material UI
- Passing function to child component from react showing it as undefined
- `throw new Error('Failed to load static props')` when setting `fallback: true` in `getStaticPaths` in Next.JS