Search code examples
javascriptreactjswysiwygreact-draft-wysiwyg

share value from one component into another in reactjs


I have used "React Draft Wysiwyg" for this. Here in the code below I want to access the value of the variable value editor.js file in the desktop.js file. how can I do that?

editor.js:



export default class TextEditor extends Component {
render(){
  return(){
        <textarea
          disabled
         value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
        ></textarea>
    
      
    );
  }
}

desktop.js:

export const Desktop = () => {

    return (
      
        <div className="splitScreen">
            <TextEditor/>

        </div>
}

Solution

  • I suggest using useState in desktop.js, while passing the state of textValue and the setState function as props to TextEditor component:

    import React, { useState } from "react";
    
    export const Desktop = () => {
      const [textValue, setTextValue] = useState("");
    
      return (
        <div className="splitScreen">
          <TextEditor textValue={textValue} setTextValue={setTextValue} />
        </div>
      );
    };
    

    And then using the two props inside TextEditor:

    import React, { Component } from "react";
    import { Editor } from "react-draft-wysiwyg";
    import { EditorState, convertToRaw } from "draft-js";
    import "./editor.css";
    import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
    import draftToHtml from "draftjs-to-html";
    
    export default class TextEditor extends Component {
      state = {
        editorState: EditorState.createEmpty(),
      };
    
      onEditorStateChange = (editorState) => {
        this.setState({
          editorState,
        });
      };
    
      render() {
        const { editorState } = this.state;
    
        // here you set the textValue state for the parent component
        this.props.setTextValue(
          draftToHtml(convertToRaw(editorState.getCurrentContent()))
        );
    
        return (
          <div className="editor">
            <Editor
              editorState={editorState}
              toolbarClassName="toolbarClassName"
              wrapperClassName="wrapperClassName"
              editorClassName="editorClassName"
              onEditorStateChange={this.onEditorStateChange}
            />
            <textarea
              disabled
              text_value={this.props.textValue} // here you use the textValue state passed as prop from the parent component
            ></textarea>
          </div>
        );
      }
    }