I'm using the DocxJS package to create a document. Inside my document, I'm trying to create a function that will iterate over some front-end props and create multiple paragraphs for each object inside the array. Whenever I iterate over the array and console.log it, it's working properly. When I do the same thing and try to use the return statement to write the "new Paragraph" as it states in the documentation, it's not working properly and returns nothing.
Here is the package and documentation: Package: https://www.npmjs.com/package/docx Documentation: https://docx.js.org/#/
My array markup looks like this:
[{item}, {item}, {item}]
The objects inside the array are:
{item.value, item.description, item.tags}
Here is the function I've created:
const createItem = () => {
let itemArray = this.props.goods.products.items;
console.log(itemArray);
// This will properly console.log the item description for each one (3 total)
itemArray.forEach((item) => {
console.log(item.description);
})
// This doesn't return anything, but the console.log DOES return the item descriptions like before
itemArray.forEach((item) => {
return new Paragraph({
text: `${item.description}`,
alignment: AlignmentType.CENTER,
style: 'educationDegree'
}, console.log(item.description));
})
}
Later on in my document that I'm creating with the docx package, I'm just calling the function like this: createItem()
I've tried passing in, createItem(this.props.goods.products.items) but it does nothing. I've tried doing: this.createItem(this.props.goods.products.items) and it just returns that this.createItem is not a function.
I just can't figure out why this isn't working properly and returning the item.description for each item as it iterates over the array? Currently it returns nothing but the console logs I'm requesting.
return new Paragraph({is happening inside. And note how you're usingforEach, notmap..forEach()method ignores values returned from the callback..map()will create a new array from the contents (modified by the callback) of an existing array.returnis not happening insidecreateItem; it's happening inside the lambda that you pass toforeach. You can't return from an outer function inside an inner function. I think you might want to change theforeachto a map, then doreturn itemArray.map((item) =>...createItemyou want to return an array of paragraphs? Then you wantmap.