Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  58] [ 4]  / answers: 1 / hits: 12706  / 4 Years ago, sat, august 15, 2020, 12:00:00

I am trying to make a rich text editor using React.js and I am using iframe with the designMode property set to 'ON'. 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 'contentWindow' of undefined. I am a beginner in React and I'm unable to figure out how to tackle this problem.


I've attached my code for your reference.


import React, { Component } from 'react'
import 'font-awesome/css/font-awesome.css'


export default class Editor extends Component {

constructor(){
super()
this.execComd = this.execComd.bind(this)
}

componentDidMount(){
let editor = this.textField.contentWindow.document
editor.designMode = 'on'
}

execComd(command){
this.textField.contentWindow.execCommand(command, false, null)
}

render() {
return (
<>
<div>
<button onClick={this.execComd('bold')}><i className="fa fa-bold"></i></button>
</div>
<iframe
ref={textField => this.textField = textField}
id="textField"
name="textField"
style={{width: "1000px",height: "500px"}}
frameborder="1">
</iframe>
</>
)
}
}

More From » reactjs

 Answers
7

You have to create a ref binded ti this,. Such as this.myRef = React.createRef(), inside the constructor. Then assign that in the render method.


ref={this.myRef}

Inside escCommand you can have now:


execComd(command){
this.myRef.current.contentWindow.execCommand(command, false, null)
}

To create a working demo of my proposal, please ignore as I have removed few unwanted code which i am not aware:


import React, { Component } from 'react'


export default class Editor extends Component {

constructor(){
super()
this.execComd = this.execComd.bind(this)
this.myRef=React.createRef();
}

componentDidMount(){

}

execComd(command){
console.log("fired");
console.log(this.myRef.current.contentWindow);

}

render() {
return (
<>
<div>
<button onClick={()=>this.execComd('bold')}>Click<i className="fa fa-bold"></i></button>
</div>
<iframe
ref={this.myRef}
title="hello"
id="textField"
name="textField"
style={{width: "1000px",height: "500px"}}
frameborder="1">
</iframe>
</>
)
}
}

[#2887] Wednesday, August 12, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
marisela questions
;