Home > Software engineering >  How to access data from one react component to another?
How to access data from one react component to another?

Time:11-28

I have three components, one App.js component which holds the other two components, (search.js, and Main.js). It's a weather application on which I'm working. user searches the city and main.js components display the relevant weather data..now I want to change the background dynamically for the full screen but for that, I need to access the API-data function in my App.js component which will provide the icon id and then I can change the background but I am confused now how to do that? I have attached the code below.

Component App.js

import React, { useState } from "react";
import "./App.css";
import Maindata from "./Components/Maindata";
import Search from "./Components/Search";

function App() {
  const [location, setLocation] = useState();

  return (
    <div className="mainpage"
    style={{
      backgroundImage: `url("./pics/01n.jpg")`,
      backgroundSize: "cover",
    }}
    >
      <div className="searchComp">
        <Search {...{ location, setLocation }} />
      </div>
      
        <Maindata city={location} />

    </div>
  );
}

export default App;

Search.js

import React, { useState } from "react";
import "../Componentstyle/search.css";

export default function Search({ setLocation }) {
  const [city, setCity] = useState("");


  const handlesubmit = (e) => {
    e.preventDefault();
    setLocation(city );
    
  };

  return (
    <div className="main">
      <nav className="istclass">
        <form className="form" onSubmit={handlesubmit}>
          <div className="search">
            <input
              value={city}
              placeholder="Search your location..."
              className="searchbox"
              onChange={(e) => setCity(e.target.value)}
            />

            <button className="nd" type="button" onClick={handlesubmit}>
            <i  aria-hidden="true"></i>
            </button>
          </div>
        </form>
      </nav>
    </div>
  );
}

Main. jsx

import React, { useState, useEffect } from "react";
// import Time from "./Time";

import moment from "moment";
import "../Componentstyle/Main.css";
export default function Maindata({ city = "mansehra" }) {
  const [data, setData] = useState();
  const [cityvalid, setCityvalid] = useState(false);

  
  const Dweather = async (city) => {
    const key = "24f4cabc9b1a10af6e3eeb4cc150a9ef";

    await fetch(
      `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${key}&units=metric&formatted=0`
    )
      .then((response) => response.json())
      .then((actualData) => {
        if (actualData.city) {
          setCityvalid(true);
          setData(actualData);
        } else {
          setCityvalid(false);
        }
      });
  };
  useEffect(() => {
    Dweather(city);
  }, [city]);

  if (!data) {
    return <div>Loading...</div>;
  }
  // if (!data.weather) {
  //   return <div>City "{city}" not recognized</div>;
  // }

  const icons = `./icons/${data.list[0].weather[0].icon}.svg`;
  const icond1 = `./icons/${data.list[7].weather[0].icon}.svg`;
  const icond2 = `./icons/${data.list[15].weather[0].icon}.svg`;
  const icond3 = `./icons/${data.list[23].weather[0].icon}.svg`;
  const icond4 = `./icons/${data.list[31].weather[0].icon}.svg`;
  const icond5 = `./icons/${data.list[39].weather[0].icon}.svg`;

  const sunrise = data.city.sunrise;
  const sunset = data.city.sunset;
  const timezone = data.city.timezone;
  return (
    <>
    
      <div
        className="newpage"
        style={{
          // backgroundImage: `url("./pics/${data.list[0].weather[0].icon}.jpg")`,
          // backgroundSize: "cover",
          flexWrap: "wrap",
          padding: "1% 10% 0 10%",
          height: "53rem",
        }}
      >
        <div className="city">
          <span className="name">{data.city.name}</span>
          <br />
          <span className="citydate">
            {moment
              .utc(new Date().setTime(data.list[0].dt * 1000))
              .add(timezone, "seconds")
              .format("dddd, MMMM Do YYYY, ")}
          </span>
        </div>
        <div className="maindata">
          {/* {!cityValid && <span>City "{city}" not found</span>} */}

          <div className="temper">
            <img src={icons} alt="not found" />
            <div className="temp">
              <span className="display">
                {" "}
                {data.list[0].main.temp.toFixed(1)}&deg;
              </span>{" "}
              <br />{" "}
              <span className="display1">
                {" "}
                {data.list[0].weather[0].description}
              </span>
            </div>
          </div>

          <div className="icon">
            {/* <img src={link} alt="not found" />{" "} */}
            <div className="acloudy">
              <span className="icon1">
                {data.list[0].main.temp_max.toFixed(1)} C&deg;
              </span>{" "}
              <br /> <span className="icon2">High </span>
            </div>
            <div className="bcloudy">
              <span className="icon1">
                {" "}
                {data.list[0].wind.speed.toFixed()} Km/h
              </span>{" "}
              <br /> <span className="icon2">Wind Speed</span>
            </div>
            <div className="ccloudy">
              <span className="icon1">
                {moment
                  .utc(sunrise, "X")
                  .add(timezone, "seconds")
                  .format("h:mm a")}{" "}
              </span>
              <br />
              <span className="icon2">Sunrise</span>
            </div>
            <div className="dcloudy">
              <span className="icon1">
                {data.list[0].main.temp_min.toFixed(1)} C&deg;
              </span>{" "}
              <br /> <span className="icon2">Low</span>
            </div>
            <div className="ecloudy">
              <span className="icon1">{data.list[0].main.humidity}%</span>{" "}
              <br /> <span className="icon2">Humadity</span>
            </div>
            <div className="fcloudy">
              <span className="icon1">
                {moment
                  .utc(sunset, "X")
                  .add(timezone, "seconds")
                  .format("h:mm a")}{" "}
              </span>
              <br /> <span className="icon2">Sunset</span>
            </div>
          </div>
        </div>

        <div className="dailyweather">
          <div className="day">
            <span className="wday">
              {moment(new Date().setTime(data.list[7].dt * 1000)).format("ddd")}
            </span>
            <br /> <img src={icond1} alt="not found" />
            <br />
            <span className="head">Temp </span>{" "}
            <span className="val">
              {data.list[7].main.temp.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Feel like </span>{" "}
            <span className="val">
              {data.list[7].main.feels_like.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Moist </span>{" "}
            <span className="val">
              {data.list[7].main.humidity.toFixed()} %
            </span>{" "}
            <br />
            <br />
            <span className="head">{data.list[7].weather[0].main}</span>
          </div>

          <div className="day">
            <span className="wday">
              {moment(new Date().setTime(data.list[15].dt * 1000)).format(
                "ddd"
              )}
            </span>{" "}
            <br />
            <img src={icond2} alt="not found" />
            <br /> <span className="head">Temp </span>{" "}
            <span className="val">
              {data.list[15].main.temp.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Feel like </span>{" "}
            <span className="val">
              {data.list[15].main.feels_like.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Moist</span>{" "}
            <span className="val">
              {" "}
              {data.list[15].main.humidity.toFixed()} %
            </span>{" "}
            <br />
            <br />
            <span className="head">{data.list[15].weather[0].main}</span>
          </div>

          <div className="day">
            <span className="wday">
              {moment(new Date().setTime(data.list[23].dt * 1000)).format(
                "ddd"
              )}
            </span>
            <br /> <img src={icond3} alt="not found" />
            <br /> <span className="head">Temp</span>{" "}
            <span className="val">
              {" "}
              {data.list[23].main.temp.toFixed(1)} C&deg;
            </span>
            <br /> <br />
            <span className="head">Feel like </span>{" "}
            <span className="val">
              {data.list[23].main.feels_like.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Moist </span>{" "}
            <span className="val">
              {data.list[23].main.humidity.toFixed()} %
            </span>{" "}
            <br />
            <br />
            <span className="head">{data.list[23].weather[0].main}</span>
          </div>

          <div className="day">
            <span className="wday">
              {moment(new Date().setTime(data.list[31].dt * 1000)).format(
                "ddd"
              )}
            </span>{" "}
            <br /> <img src={icond4} alt="not found" />
            <br /> <span className="head">Temp</span>{" "}
            <span className="val">
              {" "}
              {data.list[31].main.temp.toFixed(1)} C&deg;
            </span>
            <br /> <br />
            <span className="head">Feel like </span>{" "}
            <span className="val">
              {data.list[31].main.feels_like.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Moist </span>{" "}
            <span className="val">
              {data.list[31].main.humidity.toFixed()} %
            </span>{" "}
            <br />
            <br />
            <span className="head">{data.list[31].weather[0].main}</span>
          </div>

          <div className="day">
            <span className="wday">
              {moment(new Date().setTime(data.list[39].dt * 1000)).format(
                "ddd"
              )}
            </span>
            <br />
            <img src={icond5} alt="not found" />
            <br /> <span className="head">Temp </span>{" "}
            <span className="val">
              {data.list[39].main.temp.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Feel like </span>{" "}
            <span className="val">
              {data.list[39].main.feels_like.toFixed(1)} C&deg;
            </span>{" "}
            <br />
            <br />
            <span className="head">Moist </span>{" "}
            <span className="val">
              {data.list[39].main.humidity.toFixed()} %
            </span>{" "}
            <br />
            <br />
            <span className="head">{data.list[39].weather[0].main}</span>
          </div>
        </div>
      </div>
    </>
  );
}

CodePudding user response:

You could use a global state management tool. React comes with useContext but if you’re looking for a more robust solution, you could look into redux in combination with react-redux. Then anywhere you need the data in the application you just use useDispatch

CodePudding user response:

best solution to hit the ground running is to use React's built-in useContext hook.

Then, as the app grows, you could pivot to something like Jotai

  • Related