Reputation: 506
I want to change the temperature from Celsius to Fahrenheit (and vice-versa) but I haven't found the correct approach to tackle this, I wrote a function that does the Celsius to fahrenheit conversion but it throws me an error. So I need someone that is able to open my brain and explain this to me haha (make me understand is what I'm saying).
Here is my code: https://codepen.io/manAbl/pen/aGymRg?editors=0011
And I put in a comment the following function, that is the one that is not working:
convertingTemperature() {
const { Fahrenheit, Celcius } = this.state;
this.setState({
Fahrenheit: true,
});
const _Celcius = this.state.weather.weather && this.state.weather.main.temp;
const _Fahrenheit = Math.round(_Celcius * 5 / 9 + 32);
if(Fahrenheit) {
this.setState({ temp: _Fahrenheit })
};
}
What I want to do is hold on my state a boolean so if the fahrenheit is true, I can do the conversion and I call my function, but the reason I think is not working is because I'm pulling out the value from my weather state object, that comes from my api call. So I want to pull out that value, into a separate state so I can make the conversions with it.
--- What I want to say with this is that I want to be able to toggle between fahrenheit and celsius when clicking the temperature
Upvotes: 0
Views: 53
Reputation: 791
I updated your code to use 2 components, where the temperature, and all that is related to the temp is defined in the WeatherData
component. The temp is passed down to it using props, and is always passed down in Celcius. (NB!!!)
The main idea here is that you have two components, where the temp is passed down as a prop
to the other component. This component also handles the conversion from C to F, and when the user clicks the span, also converts the C to F, using the function getCorrectTemp()
(which also formats it as a string.
Note: remember the bind
in the onClick
event, or else the this
context is lost.
class WeatherData extends React.Component {
constructor(props) {
super(props);
this.state = { isCelcius: true }
}
toggleIsCelcius() {
this.setState({isCelcius: !this.state.isCelcius});
}
getCorrectTemp(temp, isCelcius) {
if(this.state.isCelcius) return `${this.props.tempCelcius} C`;
return `${(this.props.tempCelcius*9/5)+32} F`;
}
render() {
const { main,name,icon,country,tempCelcius } = this.props;
if(tempCelcius) {
const tempFormatted = this.getCorrectTemp(tempCelcius, this.state.isCelcius);
return (
<div className='app-wrapper'>
<p>{name},{country}</p>
<small>{main}</small>
<span onClick={this.toggleIsCelcius.bind(this)}>{tempFormatted}</span>
<img src={icon} alt=''/>
</div>
);
} else {
return <div className='app-wrapper'>Loading ...</div>
}
}
}
I also added a loading state, but you can remove this if you do not want it. Just remember to handle the state where the temp has not yet been received from the server.
Upvotes: 2