Home > Enterprise >  How to get data of input fields from previous page when next page is loaded?
How to get data of input fields from previous page when next page is loaded?

Time:10-01

when "Search" is clicked, next page is loaded by the below code.

import React from "react";
import { Link } from "react-router-dom";

function name(){
return(
 <div className="search">
    <input type="text"placeholder="city name"></input>
    <input type="text"placeholder="number of people"></input>
    <p><Link to="/nextpage">Search</Link</p>
</div>
)
}

I want to take data of these input fields to fetch api using that data to make cards on next page. How to do it?

CodePudding user response:

Here's the general idea of how you could accomplish this. You need to store the form input (in your case, the city and number of people) in application state. You can do that using the useState hook. Now this state can be managed by your first component (the one which renders the input fields) and accessed by the second component (the one that will display the values).

Because the values need to be accessed by both components, you should store the state in the parent component (see lifting state up). In my example, I used App which handles routing and renders FirstPage and SecondPage. The state values and methods to change it are passed as props.


Here's how you initialise the state in the App component:

const [city, setCity] = useState(null);
const [peopleCount, setPeopleCount] = useState(null);

city is the value, setCity is a function which enables you to modify the state. We will call setCity when the user makes a change in the input, like this:

export const FirstPage = ({ city, setCity, peopleCount, setPeopleCount }) => {

...

const handleCityChange = (e) => {
  setCity(e.target.value);
};

...

 <input
  type="text"
  placeholder="city name"
  value={city}
  onChange={handleCityChange}
/>

When a change in the input is made, the app will call the setCity function which will update the state in the parent component. The parent component can then update the SecondPage component with the value. We can do it simply by passing the value as a prop:

<NextPage city={city} peopleCount={peopleCount} />

Now you can do whatever you want with the value in your SecondPage component. Here's the full code for it, where it just displays both values:

export const NextPage = ({ city, peopleCount }) => {
return (
  <div>
    <p>city: {city}</p>
    <p># of people: {peopleCount}</p>
  </div>
);
};

And here's the full working example: https://stackblitz.com/edit/react-uccegh?file=src/App.js

Note that we don't have any field validation, and we have to manually write the change handlers for each input. In a real app you should avoid doing all this by yourself and instead use a library to help you build forms, such as Formik.

  • Related