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.
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;