Search code examples
reactjsreact-hooksreact-functional-componentreact-class-based-component

how to convert class component to function component with hooks in reactjs


My Code in Class Component

I am still new to learning React and I am having a tough time converting class components into functional components.

  class App extends React.Component {
  handleChange = (e) => {
    const { name, value } = e.target
    this.setState({
      [name]: value
    })
  }
  configureCaptcha = () => {
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {

        this.onSignInSubmit();
        console.log("Recaptca varified")
      },
      defaultCountry: "IN"
    });
  }
  onSignInSubmit = (e) => {
    e.preventDefault()
    this.configureCaptcha()
    const phoneNumber = "+91" + this.state.mobile
    console.log(phoneNumber)
    const appVerifier = window.recaptchaVerifier;
    firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
      .then((confirmationResult) => {
        window.confirmationResult = confirmationResult;
        console.log("OTP has been sent")
      }).catch((error) => {
        console.log("SMS not sent")
      });
  }

  render() {
    .....
    )
  }
}
export default App;

My output in class Component

enter image description here

how to convert class component to function component with hooks in reactjs


Solution

  • The code would look with the new syntax like this. But I would recommend to store the values of name and mobile strictly by separate useStates to make the code more clear:

    const App = () => {
      const [values, setValues] = useState({});
    
      const handleChange = (e) => {
        const { name, value } = e.target;
    
        setValues({ [name]: value, ...values });
      };
    
      const configureCaptcha = () => {
        window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
          "sign-in-button",
          {
            size: "invisible",
            callback: (response) => {
              onSignInSubmit();
              console.log("Recaptca varified");
            },
            defaultCountry: "IN",
          }
        );
      };
    
      const onSignInSubmit = (e) => {
        e.preventDefault();
        configureCaptcha();
        const phoneNumber = "+91" + values.mobile;
        console.log(phoneNumber);
        const appVerifier = window.recaptchaVerifier;
        firebase
          .auth()
          .signInWithPhoneNumber(phoneNumber, appVerifier)
          .then((confirmationResult) => {
            window.confirmationResult = confirmationResult;
            console.log("OTP has been sent");
          })
          .catch((error) => {
            console.log("SMS not sent");
          });
      };
    
      return <div></div>;
    };
    
    export default App;