Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information.

The basic details section consists of two input fields: First Name and Last Name.

However, I now have a new requirement to add a Profile Summary control, which should be a text editor allowing users to enter text that will be stored in JSON format.

For reference, please check out the JSON format provided in this link.

{
    basicDetails: {
      firstName: "",
      lastName: "",
      profileSummary: "" --------> This is where I need to fetch the text editor entered values
    },
    companyDetails: [
      {
        companyName: "",
        designation: "",
        startDate: ""
      }
    ]
  }

To implement the text editor feature, you can refer to this file: Text Editor File

Objective:

The objective is to store the text editor content within the JSON structure.

For example, text formatting such as making text bold or creating a bullet list should reflect in the value of the key profileSummary.

In order to achieve this functionality similar to this platform, you may need to explore how to convert text editor input into the JSON key profileSummary.

View a working example here:

Working Example

Your assistance on this matter would be greatly appreciated.

Answer №1

Whenever there is a change in the editorState, it is necessary to retrieve its plain HTML equivalent and then pass it to your BasicDetails component.

onEditorStateChange = (editorState) => {
  // console.log(editorState);

  this.setState({ editorState }, () => {
    // state updated

    // convert editorState to plain HTML
    const contentRaw = convertToRaw(editorState.getCurrentContent());
    const contentHTML = draftToHtml(contentRaw);

    const fakeEvent = {
      target: {
        name: this.props.name,
        value: contentHTML
      }
    };

    // call onChange function from Parent passing the
    // fakeEvent object
    this.props.onChange(fakeEvent);
  });
};

In your BasicDetails component, you need to provide onChange and name props to the EditorContainer component.

...

<EditorContainer
  name="profileSummary"
  onChange={(event) => handleInputChange(event)}
/>

Unfortunately, the functionality for converting DraftJS Editor content to plain HTML is not included in the draft-js library. Instead, they only offer support for the following data conversion functions:

  • convertFromRaw
  • convertToRaw
  • convertFromHTML

Hence, an alternative library is required. In the provided code snippet, I am using draftjs-to-html, which is created by the same individual behind react-draft-wysiwyg.

Edit To prevent setting the profileSummary with an empty p tag, we can check if the editorState contains any text before proceeding.

this.setState({ editorState }, () => {
  const currentContent = editorState.getCurrentContent();
  const contentRaw = convertToRaw(currentContent);
  const value = currentContent.hasText() ? draftToHtml(contentRaw) : "";

  const fakeEvent = {
    target: {
      name: this.props.name,
      value
    }
  };

  this.props.onChange(fakeEvent);
});

https://codesandbox.io/s/nextjs-css-only-carousel-forked-unkdk?fontsize=14&hidenavigation=1&theme=dark

Answer №2

To complete the BasicDetails section, you must create a function called handleEditorChange.

After that,

# basic_detail.js
  ...
 <div className="">
        <label htmlFor="lastName">Profile Summary</label>
        <EditorContainer  onChnage ={handleEditorChange}/>
   </div>
...

# text_editor.js

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    });
   this.props.onChange(editorState)
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Triggering an event upon completion of ng-repeat's execution

I am facing a challenge in updating the style of a specific element after ng-repeat has finished changing the DOM. The directive I have implemented for triggering ng-repeat works perfectly fine when adding items to the model, but it does not get called whe ...

The persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Price Adjuster Tracker

Recently, I coded a small JavaScript program with the purpose of: incrementing or decrementing the quantity of an item by 1 adjusting the price of an item based on the initial price However, my excitement turned to disappointment when I encountered these ...

Utilizing React Sound with React Router Dom

Currently developing a website that utilizes a router to display various pages. Chose React for its user-friendly features but encountered an issue with integrating sound. The main issue arises when switching pages, causing the sound to restart instead of ...

Transforming a string into an object

I've been working on this code where my aim is to convert a string into an object and then display the data from an ajax call. However, it appears that using the string value in this way is not functioning as expected. var string = "first: 'Geor ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

Utilize fetch API in React to streamline API responses by filtering out specific fields

I have received an API response with various fields, but I only need to extract the description and placeLocation. results: [{placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR",…},…] 0: {placeId: "BHLL ...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

Dealing with menu overflow in React using Material UI

Is there a way to ensure that the main content moves correctly in this scenario? Perhaps I need to dynamically calculate the margin-left or find a better solution altogether? Initially, everything seems fine: https://i.stack.imgur.com/S7WBd.png However, ...

React application experiencing incorrect hexadecimal hash value output in crypto function

In my Reactjs app rendered by Nextjs, I am confused about why I am receiving different hash values in the web browser when using this code: crypto.createHash('sha256').update("12345678").digest("hex"); The expected hash value from the sha256 on ...

Text displayed in dropdown when selecting autocomplete option from Material UI

I'm facing a problem with the Material UI's Autocomplete Component. The issue is that the value is being shown instead of the text element. My data source format looks like this: [{value: 'someValue', text: 'My Text'}, {value ...

The SSE functionality is effective in a local environment, but encounters issues when deployed on Vercel's

Operating a proxy server, I send a request to OpenAI which responds with a Readable Stream object. The proxy server then redirects these events back to the client. While my code functions properly on a local deployment, it encounters issues when deployed ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

The input field in Ckeditor dialogs becomes inaccessible when the editor is placed within a modal interface

Currently, I am incorporating material-ui-next dialog with CKEditor as the editor placed within the modal. In order to add LaTeX text, I have utilized the MathJax plugin. However, I have encountered an issue where I am unable to focus the input field to pr ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...