Reputation: 153
So what I want to do is take the input from the radio buttons (metric or imperial) from Forecast.js, use them in a function in Conditions.js to determine whether it's hot or cold. I've exported the variable unit from Forecast.js but when I try to use it in the clothes() function it doesn't work. I've tried everything I found online and I tried to understand but I'm new to Reactjs.
Conditions.js https://pastebin.com/RHbLuqZD
import { unit } from '../Forecast/Forecast.js';
function clothes(t) {
if (unit === "metric") {
if (Number('t') <= 20)
return (<>
<img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
It's cold, dress accordingly!
</>);
else
return (<>
<img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
It's Warm, dress accordingly!
</>);
}
if (unit === "imperial") {
if (Number('t') <= 70)
return (<>
<img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
It's cold, dress accordingly!
</>);
else
return (<>
<img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
It's Warm, dress accordingly!
</>);
}
}
Forecast.js https://pastebin.com/wcBu8bwA
export default Forecast;
export let unit = this.state.unit;
The reason it doesn't work could be because I didn't do the import and export properly or because I didn't use the imported variable properly.
Edit: As I specified I'm a beginner, I don't know a lot, what I want is to see how to solve the problem and then understand how to do it. I just need to understand the problem with my code, or an alternative.
Upvotes: 0
Views: 202
Reputation: 450
This is not how the whole thing works. One state variable like unit
in one component is not exportable like that.
There are mainly two things you can do:
unit
value to the Conditions.js
as a prop and then pass it on to the clothes
function (when using it, just like you pass the temperature value) to work with it;Upvotes: 1
Reputation: 11
if('clothes' and 'Forecast' is a parent-child realationship)
the 'unit' state, can be deliver by 'props'
function Parent(props){
const [unit,setUnit] = useState("")
return(
<Child unit={unit}>
)
}
function Child(props){
console.log(props.unit)
return(
<div/>
)
}
Upvotes: 1