Pranav
Pranav

Reputation: 1646

How to convert class component to functional component in reactjs?

I have App.js file which is written in class component but, I want to change it to functional component. Since, I'am used to class and new to functional component. Any suggestions highly appreciated... Thanks in advance

Below is my App.js file

import React from 'react';
import './App.css';
import Weather from './components/Weather';
import Form from './components/Form';
import Title from './components/Title';
import ForecastDays from './components/forecast';
import haze from './video/Haze.mp4';
import Spinner from './components/Spinner'

class App extends React.Component  { 
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      lat: '',
      lon: '',
      city: '',
      country: '',
      humidity: '',
      temperature: '',
      wind: '',
      description: '',
      error: ''
    }
  }

  componentDidMount = async () => {
    const {city, country} = this.state;

    // weatherbit
    const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/current?` + 
    `?city=${city},${country}&days=5&key=${API_KEY3}`)
    const data3 = await api_call3.json();
    console.log('DATA I GET', data4)

    // weatherbit
    const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/forecast/daily` + 
    `?city=${city},${country}&days=5&key=${API_KEY3}`)
    const data3 = await api_call3.json(); 

    this.setState({
        temperature: data4.data[0].temp,
        city: data4.data[0].city_name,
        country: data4.data[0].country_code,
        humidity: data4.data[0].rh,
        wind: data4.data[0].wind_spd,
        description: data4.data[0].weather.description,
        error: "",
        forecastdays: data3.data,
        isLoading: false
      })


  } 

  getWeather = async (e) => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

    // 1. weatherbit
    const api_call4 = await fetch(`https://api.weatherbit.io/v2.0/current?` + 
    `city=${city},${country}&key=${API_KEY3}`);
    const data4 = await api_call4.json();

    // 2. weatherbit
    const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/forecast/daily` + 
    `?city=${city},${country}&days=5&key=${API_KEY3}`)
    const data3 = await api_call3.json();

    if(city && country) {
      this.setState({
        temperature: data4.data[0].temp,
        city: data4.data[0].city_name,
        country: data4.data[0].country_code,
        humidity: data4.data[0].rh,
        wind: data4.data[0].wind_spd,
        description: data4.data[0].weather.description,
        error: "",
        forecastdays: data3.data,
        isLoading: false
      })
    } else {
      this.setState({
        temperature: undefined,
        city: undefined,
        country: undefined,
        humidity: undefined,
        description: undefined,
        error: "Please Enter Some Value"
      })
    }
  }

  render() {
    const { forecastdays, isLoading, lat,lon,city,country,humidity,temperature,wind,
    description} = this.state;

    return (
      <div className="container">
        <div className="row">

            <div className="col-sm-4 form-container">
              <Title/>
              <Form getWeather={this.getWeather}/>
            </div>
          {isLoading && <Spinner/>}
          {!isLoading && (
            <React.Fragment>
         <div className="col-sm-8 image-container">

         {/* Weather Card */}
         <div className="background">
         <div className="container">

             <div id="card" className="weather">

                 <div className="details">
                     {/* Weather Details */}
                      <div className="content" style={{width: '125px'}}>
                       <Weather
                         temperature={this.state.temperature}
                         city={this.state.city}
                         country={this.state.country}
                         humidity={this.state.humidity}
                         description={this.state.description}
                         wind={this.state.wind}
                         /> 
                      </div>

                     {/* Forecast Cards */}

                     <div className="content" style={{width: '210px'}}>
                       <ForecastDays forecastdays={forecastdays}/> 
                      </div>
                     {/* Forecast Cards Ends*/  }          
                 </div> 

             </div>
         </div>
         </div>
         {/* Video Background Starts */}
         <div>
         { this.state.description == 'Haze' ? <video autoPlay muted loop id="myVideo">
         <source src={haze} type="video/mp4"/>
       </video>: ''}
         </div>
         {/* Video Background Ends */}
         </div>
         {/* Weather Card Ends */}
         </React.Fragment>
          )}
        </div>
      </div>
    );
  }
}

export default App

I want this to convert to functional component... Please help

Upvotes: 0

Views: 941

Answers (3)

Bradley Richardson
Bradley Richardson

Reputation: 26

      const App = () => {
        const [isLoading, setIsLoading] = useState(true);
        const [weather, setWeather] = useState();
        const [error, setError] = useState();
        const [city, setCity] = useState();
        const [country, setCountry] = useState();

        useEffect(async () => {
          const result = await axios(
            "https://hn.algolia.com/api/v1/search?query=redux"
          );
          setData(result.data);

          const api_call3 = await fetch(
            `https://api.weatherbit.io/v2.0/forecast/daily` +
              `?city=${city},${country}&days=5&key=${API_KEY3}`
          );
          const data3 = await api_call3.json();
          setWeather({
            temperature: data4.data[0].temp,
            city: data4.data[0].city_name,
            country: data4.data[0].country_code,
            humidity: data4.data[0].rh,
            wind: data4.data[0].wind_spd,
            description: data4.data[0].weather.description,
            forecastdays: data3.data
          });
          setIsLoading(false);
        });
        return null;
      };

This might help you get started

Upvotes: 1

Nerdragen
Nerdragen

Reputation: 3194

First of all, I'm going to call out some extremely unhelpful behavior from @marzelin. You should be ashamed, there is absolutely no need to be pedantic about it being called a function vs functional component. If you Google "function component", you'll literally get results of people calling it "functional components", because it means the same thing, there's no difference, and you're just being mean.

Second, to answer your question, and without the extra snark, you should really read the docs. To sum it up, your current implementation you have can't be converted to a function(al) component primarily because it has a state. Why? A function(al) component is exactly that, it's just a function, and functions can't have state, as it's a React thing, not an overall Javascript thing. This is also the reason why function(al) components are called stateless components. The primary usage of these components is to be pure, and return the same output given the same input.

Upvotes: 0

Maximiliano Poggio
Maximiliano Poggio

Reputation: 1182

I won't make your job, but im glad i can explain you the difference between a stateful (class) and a stateless (function / functional / whatever you want to call it, but no state).

The stateful component has a state, and is also used like container. For instance, you could have a PageContainer where you make an ajax call in componentDidMount to retrieve information.

The stateless component is just a UI component, has no side effect. Ever. So, For instance, you will have a component <ShowInfo data={this.state.data} /> that will be rendered in your stateful component. That showinfo will be a stateless component.

Now, you can use hooks that are a mix of both: They include state in functional components. You can read lot of documentation in react docs.

Upvotes: 0

Related Questions