Reputation: 805
I am working on a project where I have to pass data from one page to another.
For example, I have data
on the first page.
let data = [
{id:1, name:'Ford', color:'Red'},
{id:2, name:'Hyundai', color:'Blue'}
]
Here is the first component page where I render this list of data with the name.
class ListDetail extends Component {
constructor();
handleClick(data){
console.log(data);
}
render() {
return (
<div>
<Hello name={this.state.name} />
<ul>
{data.map((data,i) => {
return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
})}
</ul>
</div>
);
}
}
I want to pass this data to the next page where I need this data and more data than this. I am using React Router 4. Any suggestion or help would be helpful.
Upvotes: 68
Views: 243900
Reputation: 1251
I'm using react-router-dom 6.4.3
The following, which seems to work for other/earlier versions, does not work with 6.4.3:
import { Link } from "react-router-dom";
<Link
to={{
pathname: '/details',
state: stateObj
}}>Learn More</Link>
A minor change has been made and the below works instead:
<Link
to={'/details'}
state={stateObj}>Learn More</Link>
Notice how the state object is now outside of the to object?
In the Details page, you can receive the object as follows:
import { useLocation } from "react-router-dom";
const DetailsPage: FC<{}> = (props) => {
const { state } = useLocation();
//do stuff with state obj
}
Upvotes: 8
Reputation: 71
Its very simple to pass data through navigate.( to another component)
import { useNavigate } from "react-router-dom";
const navigate=useNavigate()
"""suppose you need to pass an "value.id" with navigate ,please try this"""
onClick={() => {history( /userUpdate,{ state: { id: value.id } })}}
"""then in "userUpdate" component =>"""
import {useLocation} from 'react-router-dom'
const { state } = useLocation(); const { id } = state;
console.log(id)
"""here is the value.id"""
Upvotes: 2
Reputation: 1
State data, current data is on the Checkout.tsx
page, and pass state data on the App.tsx
page (using typescript)
import { useHistory } from 'react-router-dom';
export default function CheckoutPage() {
const history = useHistory();
const data = [
{
name: "Ngoc",
id: 1
},
{
name: "Kevin",
id: 2
},
{
name: "Jack",
id: 3
},
];
history.push({
pathname: `/app`, /* this path field is based on your project */
state: data ? data : [] /* pass state data to app page */,
});
}
import { useLocation } from 'react-router-dom';
export default function AppPage() {
const history = useHistory();
// use useLocation read data form Checkout page
const location = useLocation<any>();
const currentDataFromCheckoutPage = location.state;
// data pass show here
console.log('currentDataFromCheckoutPage', currentDataFromCheckoutPage);
}
Upvotes: 0
Reputation: 3689
Best way to pass data to the target Component, just copy paste the code and see the magic, I also explained it in depth.
Remember: in react-router-dom v6 you can use hooks instead.
version 5.X
Let's suppose we have two Components first and second. The first has the link which will target the second component.
The first Component where the link is, by clicking the link you will go to the target path as in my case it is:"/details"
.
import React from 'react';
import {Link} from 'react-router-dom';
export default function firstComponent() {
return(
<>
<Link to={{
pathname: '/details',
state: {id: 1, name: 'sabaoon', shirt: 'green'}
}} >Learn More</Link>
</>
)
}
Now in the second Component you can access the passed object as:
import React from 'react'
export default class Detials extends React.Component{
constructor(props){
super(props);
this.state={
value:this.props.location.state,
}
}
alertMessage(){
console.log(this.props.location.state.id);
}
render(){
return (
<>
{/* the below is the id we are accessing */}
hay! I am detail no {this.props.location.state.id} and my name is
{this.props.location.state.name}
<br/>
<br/>
{/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>
</>
)
}
}
note:In version 6 of react-router-dom the above method won't work on class components though you can use functional components of react by using useLocation hook and then you can draw the state object through that location in another component.
version 6
How to achieve the same using hooks v6 of react-router-dom
Let's suppose we have two functional components, first component A, second component B. The component A wants to share data to component B.
usage of hooks: (useLocation,useNavigate)
import {Link, useNavigate} from 'react-router-dom';
function ComponentA(props) {
const navigate = useNavigate();
const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
}
return (
<>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
);
}
export default ComponentA;
Now we will get the data in Component B.
import {useLocation} from 'react-router-dom';
function ComponentB() {
const location = useLocation();
return (
<>
<div>{location.state.name}</div>
</>
)
}
export default ComponentB;
Upvotes: 44
Reputation: 167
how to pass data into another compoent router in reactjs
Login.jsx
handleClickSignIn(){
console.log("come handle click fun");
this.props.history.push( {pathname: "/welcome",
state: { employee:"Steven" }});
}
welcome.jsx
componentDidMount()
{
console.log(this.props.location.state.employee);
}
Upvotes: 3
Reputation: 3908
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.
Upvotes: 111
Reputation: 347
When you want to send one page in one object same code below you must import your page in your object file and again import your page in your destination file same this:
import Home from './componenets/home/home';
import ColdDrink from './componenets/coldDrink/coldDrink';
import HotDrink from './componenets/hotDrink/hotDrink';
import CheaseCake from './componenets/cheaseCake/cheaseCake';
import Lost from './componenets/404/lost';
const link = [
{
name : "Cold Drink",
link : "/ColdDrink",
router : <ColdDrink/>
},
{
name : "Hot Drink",
link : "/HotDrink",
router : <HotDrink/>
},
{
name : "chease Cake",
link : "/CheaseCake",
router : <CheaseCake/>
},
{
name : "Home",
link : "/",
router : <Home/>
},
{
name : "",
link : "",
router : <Lost/>
}
];
and in your destination file you must map your object...
const links = (this.props.link);
{links.map((item, i) => (
{item.router}
))}
Upvotes: 0
Reputation: 96
Assuming your other page is a component you could pass the data as a prop which will be available on the next page. Something to note though, you must use <Link />
component which available in react-router 4
as opposed to using <a></a>
which causes a full page reload hence making access of the data lost.
Upvotes: 0
Reputation: 12021
You can use react-router's Link
component and do the following:
<Link to={{
pathname: '/yourPage',
state: [{id: 1, name: 'Ford', color: 'red'}]
}}> Your Page </Link>
and then access the data with this.props.location.state
You could also consider using redux for state management in your whole application (https://redux.js.org/).
Upvotes: 17