I am new to programming and started learning React a few weeks ago. I am trying to create a weather app. I created a file called Weather.js where I the fetch api data that will be displayed. One of the inputs for the api link is lat/log. I decided to create another file called Button.js, where a user will enter their lat/long and submit it. Once submitted, that lat/long will get placed on the api link (in Weather.js), to fetch that person's weather forecast. I am able to console.log the button data in Button.js. How do I pass that data to Weather.js? I think I'm supposed to use props and/or a callback function, but I am at a loss on how to do it properly. Nothing has worked so far. Thank you for your help.
function Weather() {
const [loading, setLoading] = React.useState(false)
const [maxTemp, setMaxTemp] = React.useState([])
React.useEffect(() => {
setLoading(true)
fetch("https://api.openweathermap.org/data/2.5/onecall?lat=34.1030&lon=-118.4105&units=imperial&exclude=current,minutely,hourly,alerts&appid={api}")
.then(res => res.json())
.then((data) => {
setLoading(false)
setMaxTemp(data.daily[0].temp.max)
})
}, [])
if(loading === true){
return <div>Loading...</div>
} else return(
<div>
High: {Math.round(maxTemp)} <br />
</div>
)
}
ReactDOM.render(<Weather />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
function Button(props) {
const [lat, setLat] = React.useState([])
const handleSubmit = (event) => {
console.log(lat)
event.preventDefault();
}
return(
<form onSubmit={handleSubmit}>
<input type="text" value={lat} onChange={e => setLat(e.target.value)} />
<input type="submit" value="Submit" />
</form>
)
}
ReactDOM.render(<Button />, document.getElementById("root"));
<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
renderfunction calls, which normally you should have only one in an application. Also, I see no relationship betweenWeatherandButton(I'm not going to question why it is named "Button" despite it is in fact a form). Are you sure this is exactly what your code looks like? If yes, then something is going really wrong.