reactjsreact-hook-formreact-draft-wysiwyg

react-hook-form Controller with react-draft-wysiwyg


I need some help. I was using react-final-form in my project but I've decided to change for react-hook-form. By the way, I love it, but I got stuck. :/

On my page, I'm using an editor to collect some info from a user. At the moment I'm using react-draft-wysiwyg. Here the code:

parentComponent.js

/**
 * react-hook-form library
*/
const {
    register,
    handleSubmit,
    control
} = useForm({
    mode: 'onChange'
});

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
        as={<WYSIWYGEditor />}
        name='editor'
        control={control}
        onChange={([ event ]) => event.target.value}
    />
</form>

WYSIWYGEditor.js

const WYSIWYGEditor = ({ input }) => {
    const [ editorState, setEditorState ] = useState(EditorState.createEmpty());
    const onEditorStateChange = editorState => {
        setEditorState(editorState);
    };

    return (
        <React.Fragment>
            <div className={classes.root}>
                <Editor
                    editorState={editorState}
                    wrapperClassName='wrapper-class'
                    editorClassName='editor-class'
                    onEditorStateChange={onEditorStateChange}
                />
            </div>
        </React.Fragment>
    );
};

export default WYSIWYGEditor;

PLEASE NOTE: The input prop comes from the coding with react-final-form. The input was passing the characters I was typing. So, if I leave input as props it fails because it doesn't exist. React-hook-form doesn't pass an input. I've changed that with props:

const WYSIWYGEditor = props=> {
    console.log(props)

and I get the following in the console.log when I type anything:

{name: "editor", value: undefined, onChange: ƒ}

As you can see, value is undefined. How can I structure the Controller in order to pass a value each time I type something in the editor?

Thanks for your help


Solution

  • I found a solution.

    value is undefined because obviously on component load there is nothin' to load. If you don't want to see undefined just pass defaultValue='' from the controller:

    <Controller
      as={<WYSIWYGEditor />}
      name='editor'
      control={control}
      onChange={([ event ]) => event.target.value}
      defaultValue='' <== here
    />
    

    Now, the issue that doesn't allow to return any typed value, is because I have declared the onChange from the controller. So, the right code would be:

    <Controller
      as={<WYSIWYGEditor />}
      name='editor'
      control={control}
      defaultValue=''
    />
    

    Also, in the WYSIWYGEditor.js file, you need to replace what before was input with props. The reason is that they are passing exactly the same Object, which contains a value, onChange, and onBlur function.

    Here a code sandbox with the working code: https://codesandbox.io/s/trusting-mountain-k24ys?file=/src/App.js