The pronouns order is quite complex and I fear you will need to learn that by heart in order to remember it.
So, let's start from this sentence:
Sophie has given a present to her sister: Sophie hat ihrer Schwester ein Geschenk gegeben.
In this case, we have two nouns ( sister and present) and for this reason the order is: dativ+ akkusativ
Sophie has given her a present: Sophie hat ihr ein Geschenk gegeben
In this case, we have a personal pronoun and a noun ( her and present). For this reason, the correct order is again: dativ + akkusativ
Sophie has given it to her: Sophie hat es ihr gegeben.
In this case, we have two pronouns (it and her), and the right order is akkusativ + dativ