use react-codemirror2 with functional component

I am using react-codemirror2 with a functional component and I need access to a value from local state inside the onKeyDown event handler but it seems like the context of this changes. I don’t know of any way to bind the value of this in a functional component, so how can I access the value of input inside handleKeyPress ? Do I just need to use a class based component? (My app also uses styled components but this can be ignored in the context of this question.)

const Console = () => {
  const [input, setInput] = useState('');
  
  // has a value here
  console.log('input: ', input);

  const handleKeyPress = (editor, event) => {
    if (event.keyCode === KEY_CODES.ENTER) {
      // empty here
      console.log('input: ', input);
    }
  };

  return (
    <StyledContainer>
      <IconButton disabled={true} icon={<RightOutlined />} />
      <Container>
        <CodeMirror
          value={input}
          options={{
            lineNumbers: false,
            foldGutter: false,
            styleActiveLine: false,
            autofocus: true,
            theme: 'material',
            mode: 'javascript',
          }}
          onBeforeChange={(editor, data, code) => setInput(code)}
          onKeyDown={(editor, event) => handleKeyPress(editor, event)}
        />
      </Container>
    </StyledContainer>
  );
};

Answer

I think there are 2 options:

  1. you can use react-codemirror2 as a class-based component or

  2. you can use onKeyUp event instead of the onKeyDown and get the value of the editor like this:

     const handleKeyPress = (editor, event) => {
        if (event.keyCode === KEY_CODES.ENTER) {
        // will return editor value
        console.log('input: ', editor.getValue());
        }
     };
    

Leave a Reply

Your email address will not be published. Required fields are marked *