When I want to go from a route to another with this.props.history.push("/"), also I want to send some additional data, for example: this.props.history.push('/postDetail', {data: item}). But I do not know how where to define this data in the class where we went.
Thank you in advance
You can send a prop called state that comes from the router:
this.props.history.push({
pathname: '/postDetail',
state: { data: item }
});
So now your component attached with that route will have the location prop available, inside the location object lies the state that you have passed.
More info here: https://reacttraining.com/react-router/web/api/history
Related
Although I am aware of it.
props.history.listen((location, action) => {
console.log("on route change",location);
})
But I need to implement slightly different.
let's say I want to do something on a specific path change in react router.
example- /user to /dashboard.
On destination component I want to do something(state change) if the previous path was /user
In user page, you can push with state. For example,
history.push({
pathname:'/dashboard',
state: { someState: someState }
});
And in dashboard page, you can get the state by location:
console.log(props.location.state);
You can make use of the the history prop when you are using react-router.
props.history.push('/dashboard');
It can be used to track previous routes and push method to redirect user to the desired path.
Take a look at https://reactrouter.com/web/api/history
I'm writing a component that uploads parameters to the server in promises. While the parameters are uploading I redirect to another component and send the parameters object as props, like this:
this.props.history.push('/new-page/createForm', {
parameters: this.state.parameters
});
At the create Form component, I'm receiving the props and rendering the state of the upload of the parameters, and they render as uploading (because they haven't finished uploading).
Back to the previous component, once the parameters upload promise finishes, I update the parameters object to reflect the new state, i.e, uploaded.
ParamsService.uploadParam(parameter, uploadRoot)
.then(() => {
parameter.status = 'Uploaded';
})
Now, once the parameters are uploaded, I want the create form to automatically re-render in order to reflect the new state of the parameters, but this is not happening automatically.
However, if I perform an action in the form, such as filling one of the input fields, which trigger a React rendering, the parameters show as uploaded.
Is there a way to recognize the props change in the new create form and re-render once the parameters state change to uploaded?
I've tried componentDidUpdate and getDerivedStateFromProps but such functions do not trigger when the parameters status change to uploaded.
Any help or guidance is appreciated.
see if react-url-query solve your problems.
as the example in readme, once you use the HOC like
export default addUrlProps({
urlPropsQueryConfig: {
foo: { type: UrlQueryParamTypes.number, queryParam: 'fooInUrl' }
},
})(MyComponent);
MyComponent will receive 2 props this.props.foo and this.props.onChangeFoo which allow you to get the value and allow you to change the url params ?fooInUrl
Solution for React hooks: use-query-params
I want to send a variable as a prop from a route to another in vue.
I have a vue component, Champions, using a v-for and creating a new component called ChampionCard for each character in a JSON file, and binding the current champion each time.
In ChampionCard, I just show the name and image of the champion.
I want that, when clicking on a ChampionCard, you get redirected to another component called Champion with URL champions/:champion.
But I can't find a way to send the champion data between those 2 routes.
The Champions component :
<div class="champions">
<ChampionCard v-bind:champion="champion" v-for="champion in champions" :key="champion.key">
</ChampionCard>
</div>
The ChampionCard component :
<article #click="redirectTo(champion)" class="champion">
<img class="champion-icon" :src="champion.image" :alt="champion.name">
<h2 class="champion-name"> {{ champion.name }} </h2>
</article>
redirectTo(champion) {
this.$router.push({ name: 'champion', params: { champion: champion.key }})
}
The above code is working as I get redirected to champions/championName, but I don't have access to my champion variable. What would be the best way to send it as a prop in Champion component ?
Thanks :)
My alternative is: While redirecting to champions/:champion route, just send the id of the champion (such as champions/123).
When you are redirecting to this route, you can store champion object in a global place (say store). So that you can lookup with id (123) when you're mounting the route.
One step further, if you cannot find the object in the global store, you can initiate a remote call. So that your route will not be broken if 123 is not in the store. (User can go directly to that route if they save some bookmarks of that page etc.)
To keep your object in the global place, you have different alternatives:
Simple State Management (Simple/Basic implementation)
Using Vuex
I think you can achieve what you want doing something like this:
Declare a new route:
{
path: '/champion/:championKey',
name: 'Some name',
component: ChampionComponent,
}
Then, when redirecting to this new route:
redirectTo(champion) {
this.$router.push("/champion/" + champion.key)
}
Now you can access to the url param like this:
this.$route.params.championKey // as declared in router.js
I'm getting the list of products in ProductList, in which, I need to pass the selected product object to Product.
Currently, I'm trying pass the id as a route param and get the product object again. But I want to send the entire product object from ProductList to Product.
My Route is
<Route path={joinPath(["/product", ":id?"])} component={Product} />
ProductList component Link
<Link to={"/product/" + this.props.product.Id} >{this.props.product.Name} </Link>
How to pass product object to Product as a prop?
the below one throws error in Typescript saying the following property does not exist on Link Type.
<Link to={"/product/" + this.props.product.Id} params={product}>{Name}</Link>
I tried the following questions, but none seems to have my issues.
Pass props in Link react-router
<--- this is similar to my issue, but answer doesn't work for react-router v4
react-router - pass props to handler component
React: passing in properties
The "to" property of Link can accept an object so you can pass your props like this :
<Link to={
{
pathname: "/product/" + this.props.product.Id,
myCustomProps: product
}
}>
{Name}
</Link>
Then you should be able to access them in this.props.location.myCustomProps
I would suggest using redux for retrieving the data. When you navigate to product route you can get the product details by dispatching some action.
componentDidMount() {
let productId = this.props.match.params.Id;
this.props.actions.getProduct(productId);
}
The product route should be connected with the the store.
Hope this helps.
You can try to do it through query params as in Pass object through Link in react router, which is quite ugly.
Also you can try to replace Link with some other element, e.g. button and in click listener do location change via browserHistory.push({ pathname:"/product/" + this.props.product.Id, state: this.props.product}) and and product as state property.
Simple task to pass data from one page to another made a real headache to newbie in Vue.js
Here is my router
I'm rendering a form on "/" page, which make an API request,
and I just want to pass data to another route page with another component
Is it so hard to do in Vue? It made a real headache for me today.
Get data from API, save & send to another component. How can I do it?
As Antony said, since you've already enabled props in router/index.js, you can pass parameters in router.push like this:
router.push({
name: 'events',
params: {
items: data
}
});
then you will be able to receive items as props in EventsDisplay.vue
export default {
name: 'eventsDisplay',
props: ['items'],
};
If you want to save it globally, you could use an event bus or a VueX store to contain it, then save and load it from this event bus or store when you need to access it.
If you want to pass it between those two components only, and only when accessing the second page from the first one, you can pass properties to the route argument as per this guide: https://router.vuejs.org/en/essentials/passing-props.html
Try using Vuex
In Source Component
this.$store.commit('changeDataState', this.$data);
this.$router.push({name: 'user-post-create'});
In Destination Component
created () {
console.log('state', this.$store);
this.$store.getters.Data;
}
Add props true in your vue router
{
path: "/pay-now",
name: "pay",
props: true,
component: () =>
import(/* webpackChunkName: "about" */ "../components/account/pay.vue"),
beforeEnter: AuthGuard,
},
After that pass props with router like that
this.$router.push({
name: "pay",
params: {
result:this.result,
}
});