I was unable to find this particular usage of the に particle elsewhere.
Maybe you could try a monolingual dictionary...? For example, 明鏡国語辞典 says:
に 🈩〘格助〙
➊㋖資格や見立て、名目などを表す。…として。 [...] 「本を[枕]{まくら}にする」「お土産に菓子をもらう」「お礼にひとこと」
This に can usually be rephrased as として. It can usually be translated to "as~" or "for~".
本を枕にする -- use a book as a pillow
お土産に菓子をもらう -- given sweets as a souvenir/gift
お礼にひとこと -- a word as expression of gratitude -> say something to show one's gratitude
So.. as your textbook says, the に is used to indicate the role one wants something to play: one makes 本 play the role of 枕, 菓子 the role of 土産, and ひとこと the role of お礼.
Or maybe you could try プログレッシブ和英中辞典:
に
7 〔…として〕as; for
親切にしてもらったお礼 (の印) に彼らを招待した
He invited them 「as a token of his gratitude for [in return for] their kindness.
誕生祝いに時計をもらった
He was given a watch for his birthday.
I was under the impression that the で particle is used to give context to things. So is it possible to replace に with で in the example sentence above?
Grammatically speaking, I think 「お土産/プレゼント/お礼に~」 is the correct usage, and using に sounds more correct to me (of course..), but I occasionally hear/say things like 「お土産でXXをもらった」「これ、誕生日のプレゼントでもらった」 etc. in casual conversation... (I don't hear/say 「お礼でひとこと」「XXをYYのお礼で差し上げる」, though...) So.. I think it'd be probably okay to say 「お土産・プレゼントで~~あげた・もらった」 in casual speech but you should use ~~に in formal speech, writing, exams, etc.