1

I'm working on a project, most of its components are classes, but I need to use Hooks, so i need to get ride of the classes and convert them to functional components, I know the basics about how to do it , but i get stuck of state and props this is one of the classes:

import React, { Component } from "react";
import { useHistory } from "react-router-dom";
class Description extends Component {
 render() {
  const handleSubmit = () => {
   this.props.completeTask(this.props.selectedTask, this.state);
  };
  const history = useHistory();
  return (
   <>
    <p>Completer donnees incident</p>
    <label for="description">Description:</label>
    <input
     type="text"
     id="description"
     name="description"
     onChange={(e) => this.setState({ emetteur: e.target.value })}
    />
    <br />

    <form action="/">
     <button type="button" className="btn btn-primary" onClick={handleSubmit}>
      Complete
     </button>
     <button
      type="button"
      className="btn btn-primary"
      onClick={history.goBack()}
     >
      Back
     </button>
    </form>
   </>
  );
 }
}

export default Description;

how can I use this in function :

 const handleSubmit = () => {
   this.props.completeTask(this.props.selectedTask, this.state);

1 Answer 1

1

You can destructure props in function component. Add useState to handle local state.

const Description = ({ selectedTask, completeTask }) => {
  const [state, setState] = useState({}); // local state

  const handleSubmit = () => {
    completeTask(selectedTask, state);
  };

  return (
    <>
      <p>Completer donnees incident</p>
      <label for="description">Description:</label>
      <input
        type="text"
        id="description"
        name="description"
        onChange={(e) => {
          setState({
            emetteur: e.target.value
          });
        }}
      />
      <br />

      <form action="/">
        <button
          type="button"
          className="btn btn-primary"
          onClick={handleSubmit}
        >
          Complete
        </button>
        <button
          type="button"
          className="btn btn-primary"
          onClick={history.goBack()}
        >
          Back
        </button>
      </form>
    </>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.