Using API's in your React App pt. 2

randysteele

Randy Steele

Posted on January 29, 2021

Using API's in your React App pt. 2

Today I'm going to continue working with the Open Map API we are going to see how we can make our data more dynamic. First I'm going to build out a user input field so the users of my app can enter any city they'd like and not just get the weather for one city.

To accomplish this task we will navigate back to the forecast.js component and refactor the code inside the <button> tag. Since I want my users to be able to enter any city they choose we will need to add a <form> tag, that will look something like this;

           <form onSubmit={getForecast}>
                <input
                    type="text"
                    placeholder="Enter City"
                    maxLength="50"
                    value={city}
                    onChange={(e) => setCity(e.target.value)}
                    />
                <label>
                    <input
Enter fullscreen mode Exit fullscreen mode

Now if you navigate to your browser you will see you now have an input field for city. The next thing I want to refactor is the fact that currently our temperature is being set in Kelvin(what even is that?) so we will give our users options to choose from Fahrenheit or Celcius. To accomplish this I added two radio buttons one for each unit of measure, that looks like this;

                    <input
                        type="radio"
                        name="units"
                        checked={unit === "imperial"}
                        value="imperial"
                        onChange={(e) => setUnit(e.target.value)}
                        />
                    Fahrenheit
                </label>
                <label>
                    <input
                        type="radio"
                        name="units"
                        checked={unit === "metric"}
                        value="metric"
                        onChange={(e) => setUnit(e.target.value)}
                        />
                    Celcius
                </label>
Enter fullscreen mode Exit fullscreen mode

So, what is this setUnit you might be asking. Well, I have added that to my state as you can see below, with the initial value set to 'imperial' we can use this to grab the value that the user selects then display that unit of measure.

So now if you enter a city name and select the radio button for the unit of measure you'd like you will see something like the below.

Alt Text

There we go! We have accomplished our goal of making our weather app more dynamic. Next week I will add some styling, see you then!

💖 💪 🙅 🚩
randysteele
Randy Steele

Posted on January 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related