Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass props one page to another page via react router?

In my React app I'm using react-router-dom. In App.js I have set my routes. There I have three components: /home, /customerinfo and /success.

In the home component I have a button. What I want is that when I press the button, the customerinfo component will load in full page and I want the state of the home component in the customerinfo component. This is what my Route looks like:

<Route
  path="/customerInfo"
  render={props => <CustomerInfo {...props} />}
/>

But I don't have access of the state of the home component in App.js, so it's not working.

How can I get the state of the home component in customerinfo?

I'm new in React. Please help me.

like image 979
Mustakim Avatar asked Sep 17 '25 00:09

Mustakim


1 Answers

Use redux to pass data for complex application.

But if you want to stick around using react only then you could pass data using props to Redirect Component.

When CustomerInfo button is clicked data from home Controller is passed down to customerInfo component.

import React from "react";
import { BrowserRouter as Router, Route, Link, Redirect } from "react-router-dom";

function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
        </ul>
        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/customerinfo" component={CustomerInfo} />
      </div>
    </Router>
  );
}

class Home extends React.Component {
  state = {
    redirect: false,
    data: 'data passed through home route to customer info route'
  };
  handleClick = () => {
    this.setState({
      redirect: true
    })
  }
  render () {
    if (this.state.redirect) {
      return <Redirect to={{
        pathname: '/customerinfo',
        state: { data: this.state.data }
      }} />
    } else {
      return (
        <div>
          <h2>Home</h2>
          <button onClick={this.handleClick}>CustomerInfo</button>
        </div>
      );
    }
  }
}

function CustomerInfo({ location }) {
  console.log(location)
  return (
    <div>
      <h2>{location.state.data}</h2>
    </div>
  );
}

export default BasicExample;

Hope that helps!!!

like image 198
tarzen chugh Avatar answered Sep 19 '25 15:09

tarzen chugh