0

How would one convert the class component to a functional one?

 import React, { Component } from 'react'

class Test extends Component {

 state = {
   value: "test text", 
   isInEditMode: false



 }
    
changeEditMode = () => {
    this.setState({
        isInEditMode: this.state.isInEditMode
    });
};

updateComponentValue = () => {
    this.setState({
        isInEditMode: false,
        value: this.refs.theThexInput.value
    })
}

renderEditView = () => {
    return (
        <div>
            <input type="text" defaultValue={this.state.value} ref="theThexInput" /> 
            <button onClick={this.changeEditMode}>X</button>
            <button onClick={this.updateComponentValue}>OK</button>
        </div>
    );
};

renderDefaultView = () => {
    return (
        <div onDoubleClick={this.changeEditMode}
        {this.state.value}>
</div>
};

render() {
    return this.state.isInEditMode ? 
        this.renderEditView() :
        this.renderDefaultView()
}}

export default Test;

I assume one needs to use hooks and destructioning, but not sure how to implement it. Is there a good guidline or best practice to follow?

2
  • 1
    This step-by-step guide isn't bad but I'd recommend really reading up on and building functional components with hooks first instead of just trying to follow a guide. If you're already familiar with functional components and not class components, that guide should help. Commented Nov 9, 2020 at 22:21
  • 1
    There are many guides, tutorials, and official documentation about this subject. Please try to attempt this on your own first and then post back here if you get stuck. Commented Nov 9, 2020 at 22:25

2 Answers 2

2

I gave a brief explanation of what is going on:

const Test = () => {
  // Use state to store value of text input.
  const [value, setValue] = React.useState("test text" /* initial value */);

  // Use state to store whether component is in edit mode or not.
  const [editMode, setEditMode] = React.useState(false /* initial value */);

  // Create function to handle toggling edit mode.
  // useCallback will only generate a new function when setEditMode changes
  const toggleEditMode = React.useCallback(() => {
    // toggle value using setEditMode (provided by useState)
    setEditMode(currentValue => !currentValue);
  }, [
    setEditMode
  ] /* <- dependency array - determines when function recreated */);

  // Create function to handle change of textbox value.
  // useCallback will only generate a new function when setValue changes
  const updateValue = React.useCallback(
    e => {
      // set new value using setValue (provided by useState)
      setValue(e.target.value);
    },
    [setValue] /* <- dependency array - determines when function recreated */
  );

  // NOTE: All hooks must run all the time a hook cannot come after an early return condition.
  // i.e. In this component all hooks must be before the editMode if condition.
  // This is because hooks rely on the order of execution to work and if you are removing
  // and adding hooks in subsequent renders (which react can't track fully) then you will
  // get warnings / errors.

  // Do edit mode render
  if (editMode) {
    return (
      // I changed the component to controlled can be left as uncontrolled if prefered.
      <input
        type="text"
        autoFocus
        value={value}
        onChange={updateValue}
        onBlur={toggleEditMode}
      />
    );
  }

  // Do non-edit mode render.
  return <div onDoubleClick={toggleEditMode}>{value}</div>;
};

and here is a runnable example

Sign up to request clarification or add additional context in comments.

Comments

0

I have released this npm package command line to convert class components to functional components.

It's open source. Enjoy.

https://www.npmjs.com/package/class-to-function

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.