Search code examples
javascriptreactjsreact-hooksreact-forwardref

how to reference a dom node using forward ref where the two components are in the same level


When i press enter on textarea in TextArea component the focus should go in textarea of Editor.js component.
this is my parent component.

  const Content = () => {
      
      return (
        <div>
          <TextArea />
          <Editor />
        </div>
      )
    }

textarea.js (first child)

 const TextArea = () => {
        function handleChange(e){
         //if e.target.value will be that of enter , bring focus to textarea of Editor.js  
        }
        return (
        <div>
            <textarea
            onChange={handleChange} 
            />
        </div>
        )

Editor.js

 const Editor = () => {
            return (
            <div>
                <textarea/>
            </div>
            )

Solution

  • This is How you approach it:

    
    const TextArea = React.forwardRef((props, ref) => {
      const {editorRef} = props;
      function handleChange(e) {
        //if e.target.value will be that of enter , bring focus to textarea of Editor.js
        if(editorRef.current){
          editorRef.current.focus();
        }
      }
      return (
        <div>
          <textarea ref={ref} onChange={handleChange} />
        </div>
      );
    });
    
    const Editor = React.forwardRef((props, ref) => {
      return (
        <div>
          <textarea ref={ref} />
        </div>
      );
    });
    
    const Content = () => {
      const textAreaRef = useRef();
      const EditorRef = useRef();
    
      return (
        <div>
          <TextArea ref={textAreaRef} editorRef={EditorRef}/>
          <Editor ref={EditorRef} textAreaRef={textAreaRef} />
        </div>
      );
    };
    

    here is a working sand box which you can test: https://codesandbox.io/s/stoic-varahamihira-rp84h?file=/src/App.js