Search code examples
javascriptreactjsreact-custom-hooks

Why I cannot create my own custom hook in js?


I was trying to make my Editor a custom hook so I created 'useEditor' hook like this

import { useState, useEffect } from 'react';
import ReactQuill from 'react-quill';
import MathEditor from './MathEditor';

  //some other imports
    
function useEditor() {
  const [editorHtml, setEditorHtml] = useState('');
  const [placeholder, setPlaceholder] = useState('Write something...');
  const [mathEditorVisible, setMathEditorVisible] = useState(false);
  const [expressionEditable, setExpressionEditable] = useState(false);

  const handleChange = (html) => {
    setEditorHtml(html);
  };

  //some other functions 

  const Editor = () => (
    <div>
      <ReactQuill
        onChange={handleChange}
        value={editorHtml}
        modules={modules}
        bounds='.app'
        placeholder={placeholder}
      />
      {mathEditorVisible && (
        <MathEditor
          onSaveFormula={handleSaveFormula}
          setMathEditorVisible={setMathEditorVisible}
          expressionEditable={expressionEditable}
          setExpressionEditable={setExpressionEditable}
          initialLatex=''
        />
      )}
    </div>
  );

  return {
    Editor,
    handleChange
  };
}

export default useEditor;

But when compiling this error occurs

*** Objects are not valid as a React child (found: object with keys {Editor, handleChange}). If you meant to render a collection of children, use an array instead. ***


Solution

  • You are not exporting Editor, you are exporting useEditor. You have to call useEditor to get Editor

    import useEditor from './components/useEditor';
    function App() {
      const { Editor } = useEditor();
      return (
        <div className='app'> <Editor /> </div>
      );
    }