Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor.

At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated.

Instead, the format required is JSON. Hence, I am providing the following input:

'{"text":"sample text"}'

However, this results in an error being thrown:

TypeError: Cannot read properties of undefined (reading 'type')

What could be the issue in my implementation?

function Placeholder() {
  return <div className="editor-placeholder">Enter some rich text...</div>;
}

const editorConfig = {

  // This is how I am attempting to specify the initial value.
  // No errors occur if I omit this. However, it's necessary for setting the initial value.
  editorState: '{"text":"sample text"}',

  // other parameters
};

export default function Editor() {

  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <ToolbarPlugin />
        <div className="editor-inner">
          <RichTextPlugin
            contentEditable={<ContentEditable className="editor-input" />}
            placeholder={<Placeholder />}
          />
          {/* other login components */}
        </div>
      </div>
    </LexicalComposer>
  );
}

Answer №1

I encountered a similar issue and discovered that editorState can actually be assigned to a function:

const editorConfig = {
  editorState: () => {
    const root = $getRoot();
    root.clear();
    const p = $createParagraphNode();
    p.append($createTextNode("preloaded node"));
    root.append(p);
  }
};

This solution was sourced from Lexical Playground: https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/App.tsx

For a more simplified demonstration, you can refer to this example: https://codesandbox.io/s/lexical-plain-playground-72pwge?file=/src/Editor.js:683-960

Answer №2

I encountered a similar issue when I was working with a stringified Lexical node tree. To provide some background, the content in stringified form was obtained from the Lexical Playground using their "export" feature...

The data is encapsulated within {editorState:{...}}. It appears that this format is not the conventional way for initializing the LexicalComposer. By removing this wrapper and accessing directly the {root:{...}}, the issue was resolved :)

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

Execute a script once the AngularJS view has finished loading

Just starting out with AngularJS and I've encountered an issue; I'm populating part of my view with HTML from a variable in my controller: <div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div> Everything works as expected ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

What steps can be taken to resolve the issue of Ajax not retrieving any data from

I'm struggling to identify the error in this code. I have created a search bar and implemented AJAX to automatically fetch data. Here is the HTML file: <!DOCTYPE html> <html> <head> <title></title> <script ...

Tips for layering one div on top of another div

I'm looking for guidance on how to position my button divs over my Trapezoids in an overlay fashion. Currently, I have set up an array to store the colors and utilizing the map function to match each button with its corresponding color type. When a ...

Automatically populate email fields with pre-filled form data

Looking to create an HTML form that utilizes JS/jQuery (no PHP) to capture data from "subject" and "message" fields and send an email. The goal is for the client-side code to open the user's mail client, pre-fill the subject and body with form data, a ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...

Looking to add a form within another form using AJAX? Just keep in mind that the initial form should also be inserted using AJAX

I have incorporated a form using AJAX on a Php page. Now, I am trying to add another form within that existing form which is also created using AJAX, but unfortunately, it is not functioning as expected. This serves as the parent page. <div class=" ...

How can I identify and return false if all the digits from 0 to 9 are matching with other characters in a string?

In my current project, I am focusing on filtering out numerical values only. I have implemented a phone mask using JavaScript on the front end to filter user input to a specific format such as (000)000-000, which includes numbers ranging from [2-9] and [0- ...

What are some effective ways to test asynchronous functions in React?

Looking for help to test async/Promise based methods in React components. Here is a simple example of a React component with async methods: import server from './server'; class Button extends Component { async handleClick() { if (await ca ...

Using Javascript to modify file permissions in Google Drive

I'm new to writing and seeking amazing solutions for all the issues I encounter. I have a website hosted on Google Drive, utilizing its SDK for Javascript. Everything functions exceptionally well, except for one problem. I need to adjust the permissi ...

Linking several asynchronous functions together in JavaScript

class Calculation { constructor(num) { this.num = num; } performAddition() { // code } performSubtraction() { // code } performMultiplication() { // code } performDivision() { // code } } const getResult = async ...

Issue with integrating Razorpay into a Node.js Express application

I am currently working on setting up a checkout page using nodejs and express with Razorpay as the payment gateway. The issue arises when trying to run the checkout() function by clicking the "Checkout" button within my shopping-cart.hbs file. Despite havi ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

What strategies can be employed to preserve certain fields while dynamically populating others using JSON in a form?

Currently, I am utilizing jquery Populate to dynamically fill a field with the information from the previous Firstname and Surname fields within the same form. However, an issue arises when using the Populate javascript function: $(formname).populate(newfi ...

The AngularJS view refuses to load when accessed from the browser, although the identical code successfully loads the view on

Here is the link to my plunker where the view loads as expected on Plunker's website. Check out My First Angular Single Page Application However, after downloading the files from Plunker and unzipping them on my local machine, the view does not load ...

Inserting duplicate rows from CSV using JavaScript

Currently, I am utilizing Papaparse to sum up rows with duplicate SKUs in my CSV file. I'm striving to achieve this task without the use of additional JS libraries such as D3. Here is a snippet of how my CSV data is structured: SKU,Daily total,Weekly ...

How can I begin a Next.js project in production mode using PM2?

I am looking to set up a project in pm2. Here is my folder structure: https://i.stack.imgur.com/PD3L2.png This is my package.json configuration: "scripts": { "dev": "next", "build": "next build", ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Encountering an issue upon pressing the 'calculate' button

Currently, I am delving into express node.js and attempting to execute a straightforward calculator code. However, whenever I click on the button, I do not receive any response, and there are no errors in my code either. I find myself a bit lost in figurin ...