I am trying to make a test project where I have a product list page and a checkout page now when I click on the products add to cart button it should save the data into a useState array and I should be able to pass the data from the state to the checkout page. I am kinda stuck please help
You can use the Link component from React-Router:
<Link
to={{
pathname: `/checkout/${productId}`,
state: { data:productData }
}}
/>
or you can use history.push() for example:
props.history.push({
pathname: `/checkout/${productId}`,
state: { data:productData }
});
According to this, you can consume the state like that:
const Checkout = (props) => {
const {state} = props.location
return <></>
}
Related
I have a question how do I save the value when I open a new page, who has an idea
<Link to={{ pathname: '/uppsala/category/', state: { the: 'query' } }} >
open lik in new tap
As mentioned in the documentation you can access the state passed through a link thanks to the useLocation hook:
https://v5.reactrouter.com/web/api/location
let { state } = useLocation();
console.log(state.the)
I have the following code
if (_get(this.state, 'showCheckoutSuccess') == false) {
alert("Order Failed: Not Enough Credits");
return <Redirect push to={{
pathname: '/view-cart',
}} />;
}
what it does orginally is just show a popup after redirect. But I want to be able to pass the showCheckOutSuccess info to that component to display a message on a line of the page.
I am not having any luck what I have tried doing was this:
if (_get(this.state, 'showCheckoutSuccess') == false) {
return <Redirect push to={{
state: { showCheckoutSuccess: "false" }
pathname: '/view-cart',
}} />;
}
and then using this.props.location.state.showCheckoutSuccess
this results in an error when i normally navigate to the cart page and it says that showCheckoutSuccess is undefined.
I think its because the info was never passed to it but users should still be able to get to the cart page even if this error never comes up.
You need redux or some other state manager (React Context will work too).
Or you can use the history hook.
history.push({
pathname:"/view-cart",
state:{
showCheckoutSuccess: "false"
}
});
and then access it like props.location.state.showCheckoutSuccess.
So far I've been replacing the url params' names manually when using a link component, for example:
const userIdParam = ':userId'
const routes = {
userDetails: `/users/${ userIdParam }`
}
<Link to={{
pathname: routes.userDetails.replace(userIdParam, user.id)
}}/>
Does react router support passing the params as props into the to object or something like this? I'm looking for something similar to the following:
const routes = {
userDetails: `/users/:userId`
}
<Link to={{
pathname: routes.userDetails,
props: {
userId: user.id
}
}}/>
I've been going through the typings and the docs but can't really find anything.
Yes it does.
If you want to navigate around then you can just use:
<Link to="/redirect-to-this-url"></Link>
Incase, you want to pass props via the react-router then do this.
// Initial Page
<Link to={{
pathname: "redirected-route",
state: {
variable: value // pass the extracted url params here
}
}}
</Link>
The object passed in the state of Link would be accessible here by:
// Redirected component
this.props.location.state // { variable: "value" }
On the official documentation, it says that to access the state that is passed into the component redirected to, you can use
this.props.location.state
However I'm not using class components and therefore I don't have this..
How do I access the passed state in my redirected component?
<Redirect
to={{
pathname: "/signin",
state: { from: props.location, alert: true },
}}
/>
The following function identifies is there is an alert passed in the state on Redirect. In case alert:true it displays the <div>
let location = useLocation()
function DashboardRedirectAlert() {
if (location.state?.alert) {
return <div className="alert alert-warning">Please Signin first</div>;
} else {
return <></>;
}
}
When you try to refer to functional components like the one above, make sure there is something to return always.
In the functional component , there is no this,so you can directly any state by props.''attribution''
You don't allow using this in functional component. The true code is:
Props.location.state.
In fact this keyboard removed because in class components when we want to reach functions and attributes and state use this but you use functional component,so not need use this.
It works in functional components well. To access the value in the redirected url
use
{( typeof props.location.state != "undefined" ) && props.location.state }
You also need to add a check for undefined in case you visit the page without the redirection
In a functional component the state prop is available on the location object returned from the useLocation() hook.
This example uses optional chaining to test if state exists and contains myVariable.
function LinkToComponent(props) {
return (
<Link
to={{
pathname: `/myRoute/${props.id}`,
state: { myVariable: true },
}}
>
Click me
</Link>
);
}
function LinkedToComponent(props) {
const location = useLocation();
// will render only if `myVariable` was passed as `true` in Link state
{
location.state?.myVariable && <p>my variable is true</p>;
}
}
I'm using ReactiveSearch search components to build a nice UI for my search app. I'm using the prop onQueryChange to invoke a function that uses to route to the search results page after user has submitted a search query.
How can I use React Router v4's to redirect to search results page after user has submitted query with the DataSearch component?
So far I have
<DataSearch
..
onQueryChange={
(prevQuery, nextQuery) => {
console.log("prev query: ", prevQuery);
console.log("next query: ", nextQuery);
{ nextQuery !== '' &&
<Redirect to="/results"/>,
}
}
}
I looked here and tried to change it for my use case. However, its not working.
UDPATE:
In regards to my comment below. I remembered that I had asked a similar question before, so I went to my profile to see if I could find it and I did. I combined that info with this and I believe I was able to come up with the solution:
if (redirect) {
return <Redirect to={{
pathname: '/search',
state: { pathname: this.state.redirect }
}}/>
}
For redirection it would be better to use onValueSelected (docs) since query would change everytime you type something in the searchbox (in order to fetch the suggestions).
In order to handle redirection declaratively with React router 4, you would update the state of your parent component when a value is selected and conditionally render the Redirect component from react router. For example,
Demo
class Main extends Component {
state = {
redirect: false
};
render() {
const { redirect } = this.state;
if (redirect) {
// when this renders it would redirect to the specified route
return <Redirect to="/search" />;
}
return (
<ReactiveBase
...
>
<DataSearch
...
onValueSelected={(value, cause, source) => {
// just setting the redirect state to true for redirection
this.setState({
redirect: true
});
}}
/>
</ReactiveBase>
);
}
}
An alternate way would be to use withRouter higher order component from React Router but the above method would also work.