Giving child functional component access to Ref defined in parent functional component. useRef()

2020-03-26 reactjs react-hooks react-ref

I need to access "editor" which is a ref defined in my parent component (Editor.js). My child component (Toolbar.js) has function imgChangeHandler which requires editor ref. What is the best way to do this ?

Editor.js (parent):

import React, {useRef, useState} from "react"
const editor = useRef(null);

function Editor() {
  ...
    return (
        <>
            <div className="center">

               <div
                   className="editor"
                   style={editorStyle}
                   ref={editor}
                   contentEditable={true}
                   suppressContentEditableWarning={true}
               >
                   <h1>introText</h1>
                   <p>subText</p>
               </div>
            </div>
        </>
    )
}

export default Editor

Toolbar.js (child):

import React, {useState} from "react"


function Toolbar() {
    const dispatch = useDispatch();

    const inputRef = useRef(null);
    const [selectedFile, setSelectedFile] = useState(null);

    const imgChangeHandler = e => {

        e.preventDefault();
        setSelectedFile(e.target.files[0]);

        let reader = new FileReader();
        let dataURI = reader.result;

        const img = React.createElement("img",{src: dataURI});
        editor.current.push(img); // need access to editor ref here

        if(selectedFile) {
            console.log("s");
            reader.readAsDataURL(selectedFile)
        }
    };

   ...
}

export default Toolbar

Answers

In React (almost)everything is done using callbacks. Toolbar should say (in its interface) I need to have a onImgAdded callback so it makes it explicit and it is thought as best practices. (specially if you are using TypeScript to express what the inputs are and if there are any return types expected)

But if you still insist on using ref and passing the ref down for whatever reason it is; in React you can pass props just like you pass arguments to function. So you can do <Toolbar editor={this.editorRef} /> or <Toolbar editor={this.editorRef.current} />

Related