This question already has answers here:
How to pass params with history.push/Link/Redirect in react-router v4?
(13 answers)
Closed 3 years ago.
I am using history.push in React in a specific page inside a function so that once the button is clicked it pushes to a specific page
someFunction (paramToPass) {
this.props.history.push('/abcfolder/TheFileToReceiveParam',{paramToPass });}
I want to get paramToPass in TheFileToReceiveParam when the page is open but I dont know how to do this.
Would be a big help if anyone can help.
Once you have passed your parameter this way :
this.props.history.push('/my-path', { myParam: paramToPass });
You can retrieve this parameter using the 'location' property of your destination component:
this.props.location.state.myParam;
According to the React Router documentation, here's an example of what the location object looks like:
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere'
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}
Related
This question already has answers here:
NextJS getStaticProps() never called
(5 answers)
Closed 11 months ago.
I have having a rather frustrating time with Next Js and am hoping that someone will be able to help.
We have a component and I am trying to use "getInitialProps" to pass props to a component during the server-side rending process, however, nothing seems to come through. I'm pretty sure I've tried every permeation I can think of and the props never go through. I know that the getInitialProps is being fired because I see the console.log coming through in the command line.
const HeaderMain = (props) => {
return(
<>
<h1>props.name</h1> <!-- This is blank -->
</>
);
};
HeaderMain.getInitialProps = async ({ req }) => {
console.log({ req: req }) // this works
// Do some other stuff here
return {
name: "Paul"
}
}
export default HeaderMain
If anyone could give me a point in the right direction it would be greatly appreciated.
In the end, we have decided to send the data from the main page through props to the component. It took quite a bit of digging around to see how the rendering engine works to get it to work the way we wanted it to work.
This question already has answers here:
How to get previous url in react gatsby
(4 answers)
Closed 2 years ago.
Is there any way to find the path of the page that a user is on on a Gatsby site and store it in a const so that it can be checked next to the current path the user is on? In other words if they're on the /about page, and are clicking a link to navigate to the /contact page, I need to get the paths of both so that I can check them against each other. I know I can get location.pathname for the current url, but how do I find the path that they are navigating to when the click a link?
Since your code structure isn't clear. Assuming a simple anchor tag, you can do something like this:-
<a href="/new/link" onClick={getHref}>New Link</a>
And in your getHref method
function getHref(event){
console.log(event.target.href); // should log '/new/link'
}
Check if this works in your case.
Please forgive for any typo, I havent validated it.
Gatsby exposes props (because it extends from #reach/router from React) by default on the top-level components (this means pages). You can pass it to the child components as you wish or store it in a const or in a React's state.
Without knowing any page structure, I'll provide something dummy as an example:
import React from "react"
import { graphql } from "gatsby"
const YourPage = ({ location, data }) => {
console.log('your page is ', location.pathname)
return <div>Dummy content</div>
}
export default Page
export const query = graphql`
query PageQuery {
site {
siteMetadata {
siteURL
}
}
}
`
Your information is stored under props.location, that's why you can destructure it in the component's declaration.
In the case above, I've used pathname property but you have a bunch exposed. Check it out to find out which one fits your requirements.
This question already has answers here:
setState doesn't update the state immediately [duplicate]
(15 answers)
React slow setState at console.log
(1 answer)
Closed 3 years ago.
Hello everybody
I'm a young beginner in programmtion. I'm trying to recover data from a Link to another component. Everything works except just put this recovered data in a state object with setState. I think I don't know evrything possible about setState but I'm quite lost.
I have this link which send the data "Command_ID" :
<Link to={`/produits/${Command_ID}`} className="item" params={{ Command_ID: {Command_ID}}}>
And as expected, I recover data like this and I recall it "order_id" :
state = {orderId: null};
componentDidMount() {
const order_id = this.props.match.params;
console.log(order_id);
this.setState({orderID: order_id});
console.log(this.state.orderID);
}
I can see in my console.log(order_id) the right number recover in the link part with the good "Command_ID". But when I try to put it with the setState and see in my console if it works, I just have a value of undefined for this.state.orderID
Thank you for your help :)
setState is async method , to execute something after the state is set you can pass function as second parameter for setState
this.setState({orderID: order_id}, () => console.log(this.state.orderId));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have problem with passing id to every depending on id.
I have a list of components (with different props) and need to add interaction to every component, which link to that page depends on id.
export const ResultItem = (id) =>
<div>
<Link to={{
pathname: `/idea/${id}`,
}}><button>View Recipe</button></Link>
</div>
;
Later in child component i need access to this id for make an API CALL to endpoint, with specific id to get data and render them.
class Component extends Component{
componentDidMount() {
// how can i declare variable depends on id here (i have id in url too
axios
fetch('http://localhost:50647/fund/GetFund/{id}')
(API CALL LOGIC)
}
render(){
return(
<div>
</div>
)
}
};
How can I pass id to child component via Link and declare it as variable to make an API CALL depends on id?
You can get the id like this inside your page component:
this.props.match.params.id
With your code using withRouter(component)
componentDidMount() {
axios.fetch('http://localhost:50647/fund/GetFund/{this.props.match.params.id}')
}
If you are using react-router, you can use:
this.props.match.params.id
To access a path variable (path param).
Be careful that you should use withRouter HOC to have access to routing information in props.
export default withRouter(MyComponent);
If the other answers don't work for you, maybe you can try:
const linkCustomProps = { id: 4 };
const toObject = { pathname: "/", customProps: linkCustomProps };
<Link to={toObject}>Click me</Link>;
Then you can access the value by:
this.props.location.customProps.id
BTW I'm using client-side HashRouting in my specific situation.
This question already has answers here:
Why does calling react setState method not mutate the state immediately?
(9 answers)
Closed 5 years ago.
onSelectedRow(user, clickEvent){
const state = this.state;
this.state['userId'] = clickEvent.target.getAttribute(user['mta:UserId']);
this.setState(state);
console.log(user['mta:UserId']);
console.log(this.state);
}
Okay, so when I click a table-cell in my app this function gets called.
The point of it is to take the users UserId and set the state. This UserId is later on passed down to a child component and used to get specific information. The problem is that I get the correct data in the first console.log but when I then log this.
state the userId is still null for some reason. Anyone had similiar problems?
It's most probably because you're not updating the const state, but instead trying to mutate the state itself.
Also, you don't have to make a copy of a state. You can update just the field you want to update like this:
onSelectedRow(user, clickEvent) {
this.setState({
userId: clickEvent.target.getAttribute(user['mta:UserId'])
}, () => { console.log(this.state.userId) });
console.log(user['mta:UserId']);
}
Also, your console.log won't read immediate change in the state as setState is an async action.
If you really want to read it you can pass the callback to the setState which fill fire right after the state is updated, or use React's lifecycle method componentDidUpdate().