How to change state in one page from a link click from another page?

Viewed 678

How can I change a state in a different page when a user clicks a link that takes them to that page?

for example

hompage

<Link href="/about">
  <button>click to go to about page</button>
</Link>

The user clicks the link in the homepage, then when the user gets to the about page, the state in the about page changes from false to true because the user clicked the link in the homepage.

about page

const [questionone, setQuestionone] = useState(false)

The framework is Next.js.

2 Answers

You can create structure code like this:

You must create Route like i was create in App.js below:

App.js

import { Switch, Route } from "react-router-dom";

import Homepage from "./Homepage";
import About from "./About";

const App = () => {
  return (
    <Switch>
      <Route exact path="/" component={Homepage} />
      <Route path="/about" component={About} />
    </Switch>
  );
};

export default App;

And then you create Homepage.jsx component like this below, in this case you don't need to import Link and use Link for changing the path of your router, in this case i use useHistory to change the path of router and send a state to the component of the path of route in this case /about which is the component is About.jsx:

Homepage.jsx

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

const Homepage = () => {
  const history = useHistory();

  return (
    <div>
      <button
        onClick={() => {
          history.push({
            pathname: "/about",
            state: { clickedFromHome: true }
          });
        }}
      >
        click to go to about page
      </button>
    </div>
  );
};

export default Homepage;

In About.jsx you can consume state from Homepage to change our state questionone in About Component. Example code in below:

About.jsx

import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";

const About = () => {
  const [questionone, setQuestionone] = useState(false);
  const location = useLocation();
  useEffect(() => {
    if (location.state?.clickedFromHome) {
      setQuestionone(true);
    }
  }, [location.state?.clickedFromHome]);
  console.log(location.state?.clickedFromHome);
  return <div>About{questionone.toString()}</div>;
};

export default About;

and now the state is changed in About.jsx if you click the button from Homepage to change path into '/about'

In react we need to use to attribute instead of href in Link tag
Your tag should like this .

<Link to="/about">
  <button>click to go to about page</button>
</Link>
Related