2

This is my button

<Button onClick={this.clickMe.bind(this, data)} className="ViewDetailsBtnLink">View Details</Button>

And this is the function clickMe

clickMe(data){
    console.log(data);    
}

Right now, all it does is display the data in the console. I wish to transfer the data to another page as well as redirect to the ViewDetails page which displays the data. Any help is appreciated.

AB7zz
  • 82
  • 1
  • 1
  • 6
  • You can use the history from react router, go check this HOC https://reactrouter.com/web/api/withRouter and then try to use the history prop to push to the route you want and have that as part of the state of the router. – jean182 May 27 '21 at 18:40

2 Answers2

4

You can use React Router library for routing your pages. For example first create router for your pages like this :

In your root file, or create another file called "Router.js" and render this, then you can render <Router/> component in your root file.

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

const BasicExample = () => {
  return (
    <Router>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
        </Switch>
    </Router>
  );
}

export default BasicExample;

In a file from where you want to navigate, for example Home.js :

const Home = () => {
  const history = useHistory();
  
  const clickMe = (data) => {
    history.push("/about", {data: data});  
  }
  return (
    <div>
      <h2>Home</h2>
      <button onClick={() => clickMe({name: "test"})} className="ViewDetailsBtnLink">View Details</button>
    </div>
  );
}

export default Home;

In a file where you want to access passed parameter. Here is About.js :

const About = () => {
  const history = useHistory();
  const data = history.location.state.data;
  
  return (
    <div>
      <h2>About</h2>
      <p>{JSON.stringify(data)}</p>
    </div>
  );
}

export default About;

As you can see, you can use useHistory hook to navigate to another page with parameter and to access the parameter passed from previous page.

Kishan Bharda
  • 5,446
  • 3
  • 30
  • 57
0

2 methods.

useContext and

useParams

useContext :

have a global context that holds some information you can use on every page.

https://reactjs.org/docs/context.html

useParams:

go to a page like "hello/randombitsofinformation"

which is put in the router as "hello/:slug"

then you do let slug = useParams();

and

<h1>{slug}</h1> 

will be the same as

<h1>randombitsofinformation</h1>
Alexander Hemming
  • 753
  • 1
  • 6
  • 28
  • Oh okay. But the problem is my code is inside a React Class component. How do I use useParams inside React class component? – AB7zz May 28 '21 at 07:56