How to parse data through a button from one component to another

Viewed 95

Hello I wanna know if is possible to Parse data from a button from a component to another component I know you can parse data in the following way:

<Component data = {data} />

But I wanna send it through a button because I need to change of "page" when I send the data if that makes sense ?

I did try the following (Is just an example):

const sendData= () => {
    <Component data = {data} />
    history.push("/sendData");
  };

<Button onClick={sendData} >Click to send data</Button>

I got in return the following output:

enter image description here

As you can see I was sending some data and got undefined in return, I did a similar question before but didn't got a proper answer and haven't find a way to do it.

Any tips, help, documentation is welcome.

Edit: This is what I wanna send ->

enter image description here

I wanna send all the data from a variable that hold that data to another page so I can use it there.

1 Answers

Since you need to communicate between two components where you cannot send props.

you have two options:

  1. Use a common state between the two pages (components) . You may either lift up the state or use a "not-so-local" state like react context

  2. If you have react-router setup, you can also pass data in the history location object like so and later read it using useLocation hook

in first component:

const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)

in other component:

let location = useLocation();
let state = location.state ;

here is the documentation https://reactrouter.com/web/api/location

Related