Reputation: 17
I am having trouble redirecting from one page to another in react. So basically I have express server to serve the data React requires, and after getting the data in React from the server, I want to display that result in another page by redirecting to that page.
My code for fetching the data from express is:-
function handleSubmit(e) {
var webData;
e.preventDefault();
fetch("/getResults",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "post",
body: JSON.stringify(FormInfo)
})
.then((res) => res.json())
.then((data) => {
console.log(data);
webData = data;
<Redirect to="/resultpage" /> //1
})
.catch(err => {
console.error(err);
});
console.log(webData);
<Redirect to="/resultpage" /> //2
if (webData != null) {
console.log(webData);
<Redirect to="/resultpage" /> //3
}
// .then((data) => setData(data.postName));
}
I have tried Redirecting at all three positions 1,2 and 3 but to no avail. I even tried redirecting as soon as handleSubmit
function is called, but then it just re-renders my form page.
Please help me redirect to my resultpage. Using <Link>
in my header is working but I am able to go to another page, but redirecting is not working here.
I am just self learning with no experience in React, so excuse my mistakes if I haven't followed any React standards.
Upvotes: 0
Views: 898
Reputation: 1687
If you want to redirect your React app to another internal url using React Router there are two options
Declarative using <Redirect />
in JSX as Quentin explains in his answer
Imperative by pushing a new location to history.push()
e.g. history.push('/resultpage');
https://reactrouter.com/web/api/history
Check in packages.json which version of react-router is your project using. Usually history
object should be injected in your component as a prop when that component is a child of a <Route />
Upvotes: 0
Reputation: 1267
I did this for my dropdown, writing here so you can have the clue on how to do it. First fn was called on focus and second on select.
handleSearchCity = () => {
axios
.get("https://www.example.com")
.then((d) => {
this.setState({
dataCityDropdown: d.data,
});
})
.catch((e) => {});
};
handleChangeCity = (value) => {
this.props.history.push({
pathname: "/resultpage",
state: { city: value },
});
};
And on the result page, this is how you will get data, which you transferred as STATE in handleChangeCity fn.
componentDidMount = () => {
if (this.props.location.state !== undefined) {
this.setState({
city: this.props.location.state.city,
});
}
};
Upvotes: 0
Reputation: 943570
JSX / Components have to be returned from the render function.
You can't just slap them into the middle of any old function.
When dealing with asynchronously acquired data (such as you have with Ajax) store the result in the state.
Have the render function read the state and conditionally return a React Router <Redirect>
.
Upvotes: 1