Home > Back-end >  How to convert Class component to function on react
How to convert Class component to function on react

Time:12-06

I have a customer feedback page or rather a contact page. There are a few in there. The page is written in JavaScript, React in the class component. I want to convert it to a functional component.

Below I will throw source code off the page

import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input, FormText } from "reactstrap";
import axios from "axios";

class Contacts extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "",
      email: "",
      subject: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value });
    //console.log(`${e.target.name}:${e.target.value}`);
  };
  async handleSubmit(e) {
    e.preventDefault();
    const { name, email, subject } = this.state;
    const form = await axios.post("/api/form", {
      name,
      email,
      subject
    });
  }

  render() {
    return (
      <Form className="col-xs-12 col-md-6" onSubmit={this.handleSubmit}>
        <FormGroup>
          <Label for="name">name:</Label>
          <Input type="text" name="name" onChange={this.handleChange} />
        </FormGroup>
        <FormGroup>
          <Label for="exampleEmail">Email:</Label>
          <Input type="email" name="email" onChange={this.handleChange} />
        </FormGroup>
        <FormGroup>
          <Label for="subject">Subject:</Label>
          <Input type="textarea" name="subject" onChange={this.handleChange} />
        </FormGroup>
        <Button>Submit</Button>
      </Form>
    );
  }
}

export default Contacts;

CodePudding user response:

1- first create a functional component like below:

2- add some hooks for the state:

3- Refactor functions in a new way:

4- At the end add the return section.

Finally you have something like this:

export default function Contacts() {
  const [state, setState] = useState({
    name: '',
    email: '',
    subject: '',
  });

  const handleChange = (e) => {
    setState({ [e.target.name]: e.target.value });
    //console.log(`${e.target.name}:${e.target.value}`);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const { name, email, subject } = state;
    const form = await axios.post('/api/form', {
      name,
      email,
      subject,
    });
  };

  return (
    <Form className="col-xs-12 col-md-6" onSubmit={handleSubmit}>
      <FormGroup>
        <Label for="name">name:</Label>
        <Input type="text" name="name" onChange={handleChange} />
      </FormGroup>
      <FormGroup>
        <Label for="exampleEmail">Email:</Label>
        <Input type="email" name="email" onChange={handleChange} />
      </FormGroup>
      <FormGroup>
        <Label for="subject">Subject:</Label>
        <Input type="textarea" name="subject" onChange={handleChange} />
      </FormGroup>
      <Button>Submit</Button>
    </Form>
  );
}

CodePudding user response:

const Contacts = (props) => {
    const [name, setName] = useState();
    const [email, setEmail] = useState();
    const [subject, setSubject] = useState();

    const handleChange = useCallback((setState, event) => {
        setState(event.target.value);
    }, []);
    
    const handleSubmit = useCallback(async () => {
        const response = await axios.post("/api/form", {
            name,
            email,
            subject
        });
        console.log(response)
    }, [name, email, subject]);


    return (
        <Form className="col-xs-12 col-md-6" onSubmit={handleSubmit}>
            <FormGroup>
                <Label for="name">name:</Label>
                <Input type="text" name="name" onChange={handleChange.bind(null, setName)} />
            </FormGroup>
            <FormGroup>
                <Label for="exampleEmail">Email:</Label>
                <Input type="email" name="email" onChange={handleChange.bind(null, setEmail)} />
            </FormGroup>
            <FormGroup>
                <Label for="subject">Subject:</Label>
                <Input type="textarea" name="subject" onChange={handleChange.bind(null, setSubject)} />
            </FormGroup>
            <Button>Submit</Button>
        </Form>
    );
    
}
  • Related