Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
How to get state from one component to other in a different url in REACTJS with hooks?

For example there is a input tag and a submit button in a Home Component. In the input tag I type my name and clicking on submit the path of my url change to /info and in that url I want to display the name I typed in input field.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can do this with the help of useHistory and useLocation Hooks from the react-router-dom. just initialize your components in to BrowserRouter Switch and import useHistory Hook in the component from where you want to pass the state and import useLocation in the component where you want to receive updated state from submit button.

  <Switch>
    <Route exact path="/form" component={Form} />
    <Route exact path="/data" component={Formdata} />
  </Switch>

push the path and state into object of useHistory same way to get data from useHistory create obejct of useLocation.

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

const Form = () => {
const [initstate, setInitState] = useState("");
let history = useHistory();
const HandleSubmit = (e) => {
  e.preventDefault();
  history.push("/data", initstate);
};

  return (
    <>
      <form onSubmit={HandleSubmit}>
        <input
          type="text"
          placeholder="text field"
          onChange={(e) => setInitState(e.target.value)}
        />
        <input type="submit" value="Submit" />
      </form>
    </>
  );
};

export default Form;

to get state data:

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

const Formdata = () => {
  let location = useLocation();

  console.log(location.state);

  return (
    <>
      <p>{location.state}</p>
    </>
  );
};

export default Formdata;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!