Search code examples
reactjsdraftjs

How can I scroll to specific section?


I'm using Draft JS from Facebook in React.

My draft adds decorators on text when the line starts with # Section name. In another component on my page, I want to create a link that will make it scroll down to that section when clicked.

|-------| ------------|
|Nav    | Draft editor|
|Title 1| # Title 1 |
|.      | Some text |

My decorator is pretty basic:

{
    strategy: (contentBlock: any, callback: any) => {
        const REGEX =/^(# .+)$/
        findWithRegex(REGEX, contentBlock, callback)
    },
    component: (props: any) => {
        
        return <h3>{props.children}</h3>
    }

}

My Nav link

<a onClick={()=>{
   window.scrollTo() // Scroll to Title 1 in DraftJS
}}>Title 1</a>

In the old JS days, I would figure out a way to make an ID and get the element, but it's not the react way.

Any help is appreciated. Thanks.

EDIT: Here is a codesandbox to play around


Solution

  • I don't like it and feels dirty, but in case anyone runs into similar issue, I basically created a function that turns the chapter name into an ID like so:

    const chapterToId = (txt: string): string => {
        return txt.trim().split("# ").join("").split(" ").join("-").toLowerCase()
    }
    

    I then use this function to create a # hyperlink like so:

    {chapters.map((chapter, i) => {
       const chapterId = chapterToId(chapter);
         return <a
              key={i}
              href={`#${chapterId}`}>
                   {chapter}
            </a>      
    })}
    

    In the draft JS and add the ID to the decorator like so:

    const chapters = {
      strategy: (contentBlock: any, callback: any) => {
        const REGEX = /^(# .+)$/gm;
        findWithRegex(REGEX, contentBlock, callback);
      },
      component: (props: any) => {
        const text = props.children[0].props.text;
        const id = chapterToId(text);
        return (
          <h3 id={id} className="text-2xl font-bold mt-4 mb-6">
            {props.children}
          </h3>
        );
      }
    }
    

    Working example here: https://codesandbox.io/s/book-editor-vrfqy?file=/src/components/MyDraft.tsx