Skip to content
Advertisement

Store word context objects in variable

Exploring word add-ins world. Want to create a list of paragraphs and navigate to each by click on it(some kind of table of content)

Like that: enter image description here

I have created code(on reactjs, but it does not matter which framework to use) When I click on any button the callback is invoked, no errors in console, but the navigation does not happen. Question: How can I pass some context data between Word.run calls to achieve this kind of behavior?

import * as React from 'react'
import { useEffect, useState } from 'react'

const findAllParagraphs = async () => {
  return Word.run(context => {
    const contentControls = context.document.body.paragraphs.load('text')
    return context
      .sync()
      .then(() => contentControls.items)
  })
}

export const App = ({ isOfficeInitialized }) => {
  const [paras, setParas] = useState<any[]>([])

  useEffect(() => {
    const loadParagraphs = async () => {
      setParas(await findAllParagraphs())
    }
    if (isOfficeInitialized) {
      loadParagraphs()
    }
  }, [isOfficeInitialized])

  const navToPar = async (par: Word.Paragraph) => {
    return await Word.run(async context => {
      par.select()
      return await context.sync()
    })
  }

  const renderList = () => {
    return paras.filter(({ text }) => !!text).map((par: Word.Paragraph, i) => {
      return (
        <div>
          <button onClick={() => navToPar(par)} key={i}>
            {par.text.substr(0, 30)}...
          </button>
        </div>
      )
    })
  }

  return (<div>{renderList()}</div>)
}

Advertisement

Answer

Please import this snippet into Script Lab so you can run an example of how you can solve the problem.

The cited snippet is doing a search in a document (it searches for the text “Word”), it stores each result (range) in an array of ranges (“rangesAr”) and it shows each one as an item in a listbox. Then you can select a range from the list and navigates to it. I think you can do something similar for paragraphs.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement