Stop Draftjs Editor to fire onChange on page load

  draftjs, javascript, reactjs

I have the component at the bottom, of which I use the onBlur and onChange functions to check if the field is empty and show an error message like so

const handleChange = (value) => {
    let extractedValue = value.getCurrentContent().getPlainText("u0001");

    let err = "";
    let errors = [];
    validators.forEach((validator) => {
        let currentError = validator(extractedValue);
        if (currentError) {
            errors.push(currentError);
            err = currentError;
        }
    });
    setError(err);

    onChange(extractedValue, errors);
};

<TextArea
    ref={ref}
    style={error ? { border: 'solid 2px red' } : {}}
    onChange={handleChange}
    onBlur={handleChange}
    {...otherProps}
/>

Problem is, the onChange event is fired on page load and therefore the input shows an error before the user even had time to enter a value.

import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { EditorState } from 'draft-js';
import Editor from '@draft-js-plugins/editor';
import 'draft-js/dist/Draft.css';
import 'draft-js-static-toolbar-plugin/lib/plugin.css';
import styled from 'styled-components';
import createToolbarPlugin from 'draft-js-static-toolbar-plugin';

const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];

const StyledTextArea = styled.div`
    box-sizing: border-box;
    border: solid 2px #afaea5;
    background-color: #ffffff;
    font-size: 10px;
    width: 100%;
    min-height: 50px;
    cursor: text;
    display: inline-block;

    &:focus {
        border-color: #3da10d;
    }

    .public-DraftEditor-content {
        min-height: 5em;
    }
`;

const TextArea = ({placeholder, withToolbar, onChange}) => {
    const [editorValue, setEditorValue] = useState(() =>
        EditorState.createEmpty()
    );

    const handleChange = (value) => {
        onChange(value);
        setEditorValue(value);              
    }

    const editor = useRef();

    const focus = () => {
        editor.current.focus();
    }

    return (
        <StyledTextArea onClick={focus}>
            <Editor
                ref={(element) => {
                    editor.current = element;
                }}
                editorState={editorValue}
                onChange={handleChange}
                plugins={withToolbar ? plugins : []}
                placeholder={placeholder}
                spellCheck={true}
            />
            {withToolbar ? <Toolbar /> : null}
        </StyledTextArea>
    );
};

TextArea.propTypes = {
    placeholder: PropTypes.string,
    withToolbar: PropTypes.bool
}

export default TextArea;

How can I stop the onChange event for page load only?

Source: Ask Javascript Questions

LEAVE A COMMENT