Home > front end >  How to open a new page and pass data between them in React JS
How to open a new page and pass data between them in React JS

Time:12-22

I am upgrading the searchbar of my project. I would like that when I press on one of the result a new page is opened that contains all the data of the selected object. Here is the code of the function which show the result of the search in a Link, and in theory when I press on a name I should go to the page passing the object to the new page.

{
  filteredData.length != 0 && (
    <div className="dataResult">
      {filteredData.slice(0, 3).map((obj, key) => {
        return (
          <Link
            className="dataItem"
            to={{ pathname: "/SelectedObj", state: obj }}
          >
            {obj.Name}
          </Link>
        );
      })}
    </div>
  );
}

So this part of code works, but the new page result without nothing, and i can not understand how to access to the object I have passed to the new page. Here the code of the new page.

function SelectedUser() {
  return <h1>Hello world</h1>;
}

The thing I don't understand is why it doesn't show me Hello world, other than how to access the passed object.

EDIT: I checked and I forgot to update the routing part. Now everything works, thanks.

CodePudding user response:

From Parent to Child Using Props

Try to imagine the directory structure of the app as follows: the parent component actually renders the child components in the app.

App
 └── Parent
   ├── Child1
   └── Child2

This is the simplest and most basic direction of data flow in React.

class Parent extends React.Component {state = { data : "Hello World" } 
render() {
        
        return (
            <div>
                 <Child1/>            //no data to send             
                 <Child2 dataFromParent = {this.state.data} />
            </div>
        );    }
}

Use the variable this.props.dataFromParent to obtain the data passed from parent to child.

class Child2 extends React.Component {
 render() {
         
         return (
             <div>
                 Data from parent is:{this.props.dataFromParent}
             </div>
         );
     }
 }

From Child to Parent Using Callbacks

Say you want to send a message from child1 to parent with the message "Hello, how are you?" Take the following steps:

In the Parent.js, set a callback function to take in the parameter that you have accessed from the child. Send the callback function to the child1.js as a prop.

class Parent extends React.Component {
state = { message: "" }
callbackFunction = (childData) => {
      this.setState({message: childData})
},


 render() {
        return (
            <div>
                 <Child1 parentCallback = {this.callbackFunction}/>
                 <p> {this.state.message} </p>
            </div>
        );
}
}

Pass your data using this.props.callback(dataToParent) in the child1.js.

class Child1 extends React.Component{sendData = () => {
         this.props.parentCallback("Hey Popsie, How’s it going?");
    },

render() { 
//Any time you wish to send data from child to parent component, call the sendData function.
    }
};

CodePudding user response:

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>
       )
    }

CodePudding user response:

for the link

<Link to={"dataitem"}
    state={{ state : "value" }}
>Navigate</Link>

and in the dataitem page use the useLocation to get the data like this

import { useLocation } from "react-router-dom";

   const location = useLocation();

   console.log(location.state);
  • Related