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

Retrieve static path names in Next.js using files stored in a directory

Currently, I am attempting to implement getStaticPaths in conjunction with acquired ids from JSON file names located within my public directory. My method is described as follows: export async function getStaticPaths() { const directoryPath = path.join(_ ...

What is the easiest method for querying one-to-many connections in Django?

Looking for a more efficient way to return a dictionary in JavaScript that includes data from both a Category table and Sub_category table. The desired format is 'Category1': 'Sub_cat1, Sub_cat2, ...'. Any ideas on a better approach? T ...

Retrieving Value from Dynamic Content Using jQuery `.keypress()` and `.delegate()`

I have encountered an issue with my code that is unable to retrieve the value of a specific ID on the .keypress function after using .delegate. The ID and other contents are generated dynamically through an AJAX call. $(document).delegate('.edit_ ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Navigate to the specified URL once the Ajax function has completed successfully

I'm having trouble with opening a URL from an Ajax function. It seems like the URL is not being called. This is the code I am using: $(document).on( "click",".btndriver", function() { var id = $(this).attr("id"); var nombre = $(this).att ...

Creating a custom Chrome extension with the ability to modify the pop-up window instead of the web page

Is there a way to modify the content inside my extension's pop-up without affecting the web page being viewed by the user? Also, how can I ensure that my dropdown list functions correctly? I have two dropdown lists where selecting an option from the ...

I'm looking to add a price ticker to my html webpage. Does anyone know how to do this?

PHP Code <?php $url = "https://www.bitstamp.net/api/ticker/"; $fgc = file_get_contents($url); $json = json_decode($fgc, true); $price = $json["last"]; $high = $json["high"]; $low = $json["low"]; $date = date("m-d-Y - h:i:sa"); $open = $json["open"]; ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

Is there a way to place a Next.js application into maintenance mode on Vercel?

After successfully launching my nextjs application on Vercel, I've been thoroughly impressed with the overall process. However, there is one minor aspect that I wish could be improved: the ability to easily activate a maintenance mode for my app. Unf ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else ...

Node responds with a 404 error upon receiving the post request

I am facing an issue with my jQuery code. Here is what I have: $.ajax( { type: 'POST', data : mydata, url : '/routerfunction', dataType : 'String', success : function(data) ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

The intricacies of the Jscript ReadLine() function

I am trying to figure out how to read the complete content of a .txt file using JavaScript. I know that ReadLine() can be used to read a specific line from a file, but I need a method that will allow me to read the entire contents of the file. I have searc ...

Ensuring the Safety of Access Tokens Automatically Generated for Firebase Storage Uploads on the Client Side

When uploading a file to Firebase Storage using the uploadBytes function from the Firebase client SDK, it automatically generates a download token and includes it in the response. Even though strict rules are set to prevent public read access, the presence ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Utilize new metadata options to incorporate an external style and script file

I'm looking to incorporate external CSS and scripts into my NextJS app (NextJS version 13.4.13). Here's what I need: Style https://company.com/statics/1/package/dist/1/styles/dls.min.css Script https://company.com/statics/1/package/dist/1/ ...

Ensuring the safety of ajax GET/POST communication between client and server

Let's say I'm working with a specific API and my file server.php is responsible for connecting to the API service. On the client side, I am using an AJAX call like this: $http({ url : 'server/server.php', method : &ap ...