mee_0w0
@mee_0w0

Как заменить компонент по нажатию кнопки?

Я пишу сайт на React для отображения погоды по геолокации, IP и ввода города вручную и я без понятия, как можно реализовать смену компонентов по нажатию кнопки. Нужно нажать на кнопку 'change city' и тебя должно перекинуть на форму, в которой ты можешь написать название города и получить результат с погодой.

компонент с отображением погоды
import { useEffect, useState } from "react";
import { v4 } from "uuid";

function ResultWeather() {
  const API_key = " "; // API Key openweathermap.org
  const IP_key = " "; // API Key ipify.org

  const [userLocation, setUserLocation] = useState([]);
  const [errorGeolocation, setErrorGeolocation] = useState();
  const [userIp, setUserIp] = useState("");
  const [ipLocation, setIpLocation] = useState([]);
  const [weatherIpLocation, setWeatherIpLocation] = useState([]);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        fetch(
          `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=daily,hourly,minutely&units=metric&appid=${API_key}`,
        )
          .then((res) => res.json())
          .then((res) => {
            setUserLocation(res);
          })
          .catch((err) => console.error("Error UserLocation: ", err));
      },
      (error) => {
        console.error("Error Geolocation: ", error);
        setErrorGeolocation(false);
      },
    );
    fetch("https://api.ipify.org?format=json")
      .then((res) => res.json())
      .then((res) => {
        setUserIp(res.ip);
      })
      .catch((err) => console.error("Error UserIp: ", err));
    fetch(
      `https://geo.ipify.org/api/v2/country,city?apiKey=${IP_key}&ipAddress=${userIp}`,
    )
      .then((res) => res.json())
      .then((res) => {
        setIpLocation(res.location.city);
      })
      .catch((err) => console.error("Error IpLocation: ", err));
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${ipLocation}&units=metric&appid=${API_key}`,
    )
      .then((res) => res.json())
      .then((res) => {
        setWeatherIpLocation(res.main.temp);
      })
      .catch((err) => console.error("Error weatherIpLocation: ", err));
  }, [ipLocation, weatherIpLocation]);

  function changeCity(e) {
    e.preventDefault();


  }

  return (
    <div className="result-weather">
      {errorGeolocation ? (
        userLocation.map((item) => {
          return (
            <div key={v4()}>
              <div className="result-degrees">
                {Math.round(item.current.temp)}°C
              </div>
              <div className="location-degrees">Windy in your location</div>
            </div>
          );
        })
      ) : (
        <div key={v4()}>
          <div className="result-degrees">
            {Math.round(weatherIpLocation)}°C
          </div>
          <div className="location-degrees">Windy in {ipLocation}</div>
        </div>
      )}
      <button className="change-btn" onClick={changeCity}>
        Change city
      </button>
    </div>
  );
}

export default ResultWeather;

компонент с формой поиска
import { useState, useEffect } from "react";

function ChangeCity() {
  const API_key = " "; // API Key openweathermap.org

  const [userCity, setUserCity] = useState("");
  const [weatherCity, setWeatherCity] = useState([]);

  useEffect(() => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${userCity}&units=metric&appid=${API_key}`,
    )
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
        setWeatherCity(res);
      });
  }, [userCity]);

  function find(e) {
    e.preventDefault();
    console.log(weatherCity);
  }

  return (
    <form className="find-form">
      <input
        type="text"
        className="search-city"
        placeholder="Type your city here"
        onChange={(e) => setUserCity(e.currentTarget.value)}></input>

      <hr className="hr-line" />
      <button className="find-btn" onClick={find}>
        Find
      </button>
    </form>
  );
}

export default ChangeCity;

6509be7723e06343666747.png
  • Вопрос задан
  • 147 просмотров
Решения вопроса 1
shamilist
@shamilist
Аналитик
Привет.

Для этих целей нужно использовать React router.
https://reactrouter.com/en/main/start/tutorial - вот здесь расписано, как это можно сделать.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
28 сент. 2024, в 00:22
10000 руб./за проект
27 сент. 2024, в 22:35
5000 руб./за проект