Use InputCity Component
Learn how to call an API using a dynamic value.
We'll cover the following
We’ll now pass the values into the onSubmitHandler
, city
, and onInputHandler
props that we used in the InputCity
component in the previous lesson.
Add the city
prop
The city
prop stores the city
value given by the user. We’ll do this by using the useState
hook. The snippet below demonstrates how to add the city prop.
const [inputCity, setInputCity] = useState("Seattle");
<InputCity
city={inputCity}
/>
We chose Seattle as the initial state because we’ll show the weather information for “Seattle” on the app’s initial rendering. The search bar should also show “Seattle” as the input value.
Add the onInputHandler
prop
The onInputHandler()
function calls the inputHandler()
function, which changes the value of the city. It does so using the setInputCity
function as it’s shown above to update the state of the inputCity
. Here’s how we do it:
// Input element handler
const inputHandler = (e) => {
setInputCity(e.target.value);
};
<InputCity
city={inputCity}
onInputHandler={inputHandler}
/>
Add the onSubmitHandler
prop
The onSubmitHandler
function calls the onSubmit
function, which updates our new state. We send this state in our API to call with the appropriate city name. We add another useState
hook with cityName
as the current state and setCityName
as the state update function. The following snippet shows how to add the submitHandler
function:
const [cityName, setCityName] = useState("Seattle");
// Search button
const submitHandler = (e) => {
e.preventDefault();
setCityName(inputCity);
};
<InputCity
city={inputCity}
onInputHandler={inputHandler}
onSubmitHandler={submitHandler}
/>
Here, e.preventDefault()
prevents the page from refreshing upon value submission. We give Seattle
as the initial state because our API takes Seattle
as the default city to render the weather information.
Combining the code snippets above produces the following code widget:
Get hands-on with 1400+ tech skills courses.