Cannot read property ‘contentDocument’ of undefined when using execCommand in React.js

I want to make the selected text bold on click of a button. I want to use the execCommand() function but I keep getting this error: TypeError: Cannot read property ‘contentDocument’ of undefined.

import React, { useEffect } from 'react'
import "./MainText.css"
import "./App.css";
import FormatColorFillIcon from '@material-ui/icons/FormatColorFill';
import BorderColorIcon from '@material-ui/icons/BorderColor';

function MainText() {

    function enableEditMode() {
        const textpart = document.getElementsByName('textPart')[0];
        const iframeDocument= textpart.contentDocument || textpart.contentWindow.document;
        iframeDocument.designMode = "on";
        iframeDocument.contentEditable = true;
    }

    useEffect(() => {
        enableEditMode();
    }, [])

    function execCmd(command) {
        const textpart = document.getElementsByName('textPart')[0];
        const iframeDocument= textpart.contentDocument || textpart.contentWindow.document;
        iframeDocument.execCommand(command, false, null);
    }

    return (
        <div className="mainText">
            <button onClick={execCmd('bold')}><i class="fa fa-bold"></i></button>
            <div className="mainText__second">
                <iframe name="textPart" frameBorder="0" ></iframe>
            </div>
        </div>
    )

please help in this.

Answer

It looks like this may be because your are assigning the result of calling the execCmd() function to the onClick property – rather than an actual function expression as is expected. In this case the execCmd(‘bold’) expression is evaluated even before the DOM actually has a chance to be mounted.

Try something like this instead:

onClick={() => execCmd('bold')}