0
...
import { useNavigate, NavigateFunction } from "react-router";
...

function Form(): JSX.Element {
  const navigate: NavigateFunction = useNavigate();
  const [country, setCountry] = useState<string>(" ");

  
  const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
    setCountry(e.target.value);
  };

  const handleSubmit = (e: FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    navigate("/country");
  };



  return (
    <Box component="form" onSubmit={handleSubmit}>
      <input
        type={"text"}
        required
        placeholder="Enter Country"
        value={country}
        onChange={handleChange}
      ></input>
      <Button variant={"contained"} type="submit">
        Search
      </Button>
    </Box>
  );
}
export default Form;

this is my index.tsx file:

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App />} />
        <Route path="/country"  element={<CountryDetails   />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

this is my CountryDetails.tsx file:

const CountryDetails = (): JSX.Element => {
    const country: string | undefined = useParams().name;

    
    return (

       
        <Box>
           hi ${country}
        </Box>
    )
}
export default CountryDetails;

I want to send the country variable from Form.tsx to CountryDetails.tsx file. How do I send it. I am doing the route operations in index file. I tried to send it as props, as state also, even used link to instead of navigate function. Used history.push too. Please help.

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Akhil
  • 1
  • `useParams` hook is for route path params, i.e. `"/path/:param1/:param2"` whereas you are sending route state, which should be accessed in the receiving component via `location.state`. Don't forget to also call `.preventDefault()` on the form's `onSubmit` event object so it's not reloading your entire app. – Drew Reese Mar 21 '22 at 04:09

1 Answers1

0

Can you try this?

<form onSubmit={() => navigate('/country', { state={ country }, replace=true })}>
  {...}
</form>

const params = useParams()
const { state } = params;
// I think country inside state
salagoz
  • 25
  • 3
  • I tried the exact same thing, there are no errors but I think i am printing it in the wrong way in CountryDetails.tsx file. And also do i have to add anything in index file for CountryDetails' element? – Akhil Mar 19 '22 at 19:09
  • Can you print the params variable to log? And why use useParams().name ? – salagoz Mar 19 '22 at 20:41
  • It is getting passed as undefined in CountryDetails.tsx page – Akhil Mar 20 '22 at 03:20