React-router - How to pass data between pages in React?
You can use the Link component from react-router and specify to={}
as an object where you specify pathname as the route to go to. Then add a variable e.g. data
to hold the value you want to pass on. See the example below.
Using the <Link />
component:
<Link
to={{
pathname: "/page",
state: data // your data array of objects
}}
>
Using history.push()
this.props.history.push({
pathname: '/page',
state: data // your data array of objects
})
Using either of the above options you can now access data
on the location object as per the below in your page component.
render() {
const { state } = this.props.location
return (
// render logic here
)
}
You can see an example of how to pass a value along with a route in another example here.
How to pass data between pages in React with react-router-dom v6?
I have solved this by following a documentation for upgrading to v6 react-router-dom and it finalllllly worked. Here it is: https://reactrouter.com/docs/en/v6/getting-started/tutorial
The solution was simple. I was just looking for a better documentation for upgrading from v5 to v6, I guess.
Also, I will attach the code if it's gonna help anybody here. (I have renamed a few things like 'DUMMY_DATA' to 'items' just for my convenience. The code would explain it clearly anyway ). If there are any doubts further, do comment and I'll try to reply! :)
GridList.js
import React from "react";
import ReactDOM from "react-dom";
import { Link, useParams } from "react-router-dom";
import { Component } from "react";
import GridItem from "./GridItem";
import AppPage from "./AppPage";
import classes from "./GridList.module.css";
import { getItems } from "./Data";
let items = getItems();
const GridList = (props) => {
return (
<div className={classes.gridc1}>
{items.map((item) => {
return (
<div key={item.id}>
<Link to={`/apppage/${item.id}`} key={item.id}>
<GridItem key={item.id} image={item.image} />
</Link>
</div>
);
})}
</div>
);
};
export default GridList;
Data.js
import React from "react";
import ReactDOM, { render } from "react-dom";
import App01 from "./app-01.png";
import App02 from "./app-02.png";
let items = [
{
title: "tic tac toe",
id: 1,
image: App01,
},
{
title: "bytes",
id: 2,
image: App02,
},
];
export function getItems() {
return items;
}
export function getItem(id) {
return items.find((item) => item.id === id);
}
AppPage.js
import React from "react";
import ReactDOM, { render } from "react-dom";
import { useParams } from "react-router-dom";
import { Component } from "react";
import { getItem } from "./Data";
const AppPage = _ => {
let params = useParams();
let item = getItem(parseInt(params.id, 10));
return (
<div>
<p ptitle = {item.title} />
<p pid = {item.id}> />
</div>
);
};
export default AppPage;
How to open a new page and pass data between them in React JS
To access the object passed to the new page,
use useLocation hook which is a function that returns the location object that contains information about the current URL. Whenever the URL changes, a new location object will be returned.
import { useLocation } from "react-router-dom";
function SelectedUser() {
const location = useLocation();
console.log(location.state);
return (
<h1>Hello world</h1>
)
}
How to send result data from one page to another page in React
You can simply pass the data along with the route push/replace.
Using the Redirect component with existing implementation
<Redirect
to={{
pathname: "/result",
state: {
value:
"$" +
Math.floor(1.69 * this.state.square * (10 / 100)) +
"- $" +
Math.floor(1.69 * this.state.square * (30 / 100))
}
}}
/>
Since your components are being directly rendered by a Route
component they are passed route props. This means that Calculator
has access to the history
prop to imperatively redirect, and Result
can access the location
prop to get the route state.
Calculator.js
Update the submit handler to do the redirect to the "/result" route and pass along the state. Remove the div
at the end of the return with Result
, you don't need that on this page. Use history.push
if you want the user to be able to go back to form.
handleSubmit = (event) => {
event.preventDefault();
this.props.history.replace({
pathname: "/result",
state: {
value:
"Your saving range is: $" +
Math.floor(1.69 * this.state.square * (10 / 100)) +
"- $" +
Math.floor(1.69 * this.state.square * (30 / 100))
}
});
};
Result.js
Just need to access the route state props.location.state.value
.
class Result extends Component {
render() {
return (
<div className="result">
<h2>You could save between</h2>
<h1>{this.props.location.state.value}</h1> // <-- route state
<NavLink to="/">Use Calculator Again</NavLink>
</div>
);
}
}
Important
Make sure your routes and app code are wrapped in a router! Swap the order of your routes so you specify more specific routes before less specific routes. This is so the Switch
can try matching more specific routes first, then falling back to the less specific ones.
...
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
...
function App() {
return (
<div className="App">
<Router> // <-- need to wrap app in Router so routes work correctly
<Switch>
<Route path="/result" component={Result} />
<Route path="/" component={Calculator} />
</Switch>
</Router>
</div>
);
}
passing data from one component to another with react router v6
Release of React Router 6 brought huge changes to api.
You can pass the state from Component 1 to Component 2 like:
Pass your state from Component 1 as follow:
navigate('/your-route', { state : { query : ' your-query ' }})
You can recieve state in Component 2 as follow:
const { state } = useLocation();
const { query } = state;
Above solution works for only React Router v6.
ReactJS How to transfer data between pages?
There are a few different ways... Good option would be to use some state management layer like Redux or MobX
A simple one is to have your Main
component save those data in its state and pass it to the other pages as props. Since you're using react-router
you'll need to clone the this.props.children
in your Main
component to add the additional props like the data and the function that sets the data.
Your Main
component would probably look something like
class Main extends Component {
constructor(props) {
this.state = {
data: 'some default data',
}
}
updateData(data) {
this.setState({ data });
}
render() {
return <div>
<Header />
{React.cloneElement(this.props.children, { data: this.state.data, setData: this.updateData })}
</div>
}
}
class MainPage extends Component {
render() {
return <div>
<input type="text" onChange={e => this.props.setData({ field: e.target.value })} />
<Link to="/DisplayResults">Go to Results</Link>
</div>
}
}
class DisplayResults extends Component {
render() {
return <div>
{this.props.data.field}
</div>
}
}
Related Topics
Allow Google Chrome to Use Xmlhttprequest to Load a Url from a Local File
Differencebetween 'New Object()' and Object Literal Notation
Getting All Variables in Scope
Maximum Size of an Array in JavaScript
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
Are Trailing Commas in Arrays and Objects Part of the Spec
How to Find Index of All Occurrences of Element in Array
Logical Operators in JavaScript - How to Use Them
What Does "This" Mean in Jquery
Please Explain the Use of JavaScript Closures in Loops
How to Determine User's Locale Within Browser
Jquery How to Bind Onclick Event to Dynamically Added HTML Element
Jquery Xml Error ' No 'Access-Control-Allow-Origin' Header Is Present on the Requested Resource.'
Adding Click Event Listener to Elements with the Same Class