Reputation: 227
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>
</>
)
}
}
Upvotes: 5
Views: 18629
Reputation: 1828
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>
</>
)
}
}
Upvotes: 2