1

With React Class Component, I use some variable (not this.state) helping my control logic. Example: this.isPressBackspace = false and when I set variable don't make component re-render (ex: this.isPressBackspace = true).

That's working perfect in Class Component but when I change to Function Component, I dont know where to place this.isPressBackspace.

Here is my example in codesandbox. https://codesandbox.io/s/function-component-example-3h98d

3
  • Did you try to use Hooks instead? Commented Oct 15, 2020 at 10:17
  • 1
    You have to use useState and modify the state Here I have converted your code take a look. codesandbox.io/s/function-component-example-forked-0fkl3 Commented Oct 15, 2020 at 10:27
  • @DipankarMaikap thank, but I dont want use useState. Do you know other solution ? Commented Oct 15, 2020 at 10:47

2 Answers 2

1

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

const isPressBackspaceRef = React.useRef(false);
const keyDownPositionRef = React.useRef({});
const onKeyDown = (e) => {
    // this is wrong syntax
    // this.keyDownPosition OR let keyDownPosition
    keyDownPositionRef.current = {
      start: e.target.selectionStart,
      end: e.target.selectionEnd
    };
    switch (e.key) {
      case "Backspace":
        isPressBackspaceRef.current = true; // this is wrong syntax ????
        break;
      default:
        break;
    }
  };
const onChange = (e) => {
    const { end } = keyDownPositionRef;
    if (isPressBackspaceRef.current) {
      const length = end - e.target.selectionEnd;
      alert(`You delete ${length} character`);
    }
    isPressBackspaceRef.current = false;
};
Sign up to request clarification or add additional context in comments.

Comments

0

In my experience you don't use the this keyword when working with function components. Instead you use hooks like useState. Check the following video for getting started with hooks: https://www.youtube.com/watch?v=O6P86uwfdR0&ab_channel=WebDevSimplified

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.