BarakJob
BarakJob

Reputation: 51

Pass the data from one component to another component (not a child)?

I want to pass data (on click) from one component(A) to another component(B) but A is not child of B.

Suppose there is a form component(A), where we want to fill the required fields, and after hitting continue button, we want to display all values in next component(B).

Upvotes: 1

Views: 939

Answers (3)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

You can use React Portals which allow to render a component in any place in application dom and you can pass the props from the controlling component.

Read the docs https://reactjs.org/docs/portals.html

render() {
  // React does *not* create a new div. It renders the children into `domNode`.
  // `domNode` is any valid DOM node, regardless of its location in the DOM.
  return ReactDOM.createPortal(
    <YourComponent prop1={value1} prop2={value2}/>,
    domNode
  );
}

Upvotes: 1

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

You either use react context API or redux to share state among components.

Or if you want to pass data only while navigating you can use history.push function and pass data in state object as below

history.push({pathname: 'yourlocation', state: { data: your data}})

And you can accesss that data in the other component using

this.props.history.location.state

Please note that you have to wrap your components using withRouter to get acess to history object

Upvotes: 0

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You can use the Link from react-router-dom to pass data.

<Link
  to={{
    pathname: "/courses",
    state: { fromDashboard: true }
  }}
/>

In the above code state object can be accessed in the history object which can be imported from useHistory hook from react-router-dom.

Upvotes: 0

Related Questions