javascriptace-editorreact-ace

Set a multiline string as defaultValue in react-ace Ace Editor


When using the react-ace (Ace Editor) library, I find myself in the need to define the defaultValue property as a code block in the JSX format (the editor mode I have left in JavaScript), like this:

<div style={{height: "100%", width:"100%"}}>
  <AceEditor
      mode="javascript"
      theme="github"
      onChange={this.onChange}
      name="UNIQUE_ID_OF_DIV"
      defaultValue="export default function MyComponent({ children }) {..."
      width="100%"
      height="100%"
      editorProps={{
          $blockScrolling: true
      }}
  />
</div>

When declaring defaultValue to get something like this:

export default function MyComponent({ children }) {
    return (
    <>
      <header>
        <a>
          <Image
            priority
            className={utilStyles.borderCircle}
            height={108}
            width={108}
            alt={name}
          />
        </a>
        <h2 className={utilStyles.headingLg}>
          <a className={utilStyles.colorInherit}>{name}</a>
        </h2>
      </header>
      <main>{children}</main>
        {!home && (
          <div className={styles.backToHome}>
            <a>← Home</a>
          </div>
        )}
    </>
  )
}

The editor returns...

Code editor description

How can I get a multiline string into the editor as a default value?


Solution

  • You can use template literals to do the multiline statements. In the official docs of AceEditor mentioned that you can pass a string for value attribute which should be reflected in the editor so when you pass a string inside " " it should not take new line so, when you use template literals ie,${``} we can give multiline sentences

    so, its similar to how we pass a value in react to attributes

    attribute-name = {"here we specify what should be the value"}

    as in our case it should be a string which can be in multiple line

    so attribute-name = {${``}}

    Example:

    value={`${`
    //firstline
    //secondline
    ...
    //n line`}`}
    

    reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals