All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His Slave and Messenger.
Under these circumstances, the fetus is to be washed, shrouded, and prayed over. This is the opinion of many of the scholars of Fiqh, due to what was established from the Prophet, sallallaahu ‘alayhi wa sallam, that he said: “The stillborn is prayed over and forgiveness and mercy are asked for its parents.” [Ahmad, Abu Daawood, Ibn Hibbaan and Al-Haakim: Saheeh; Al-Albaani: Saheeh]
The meaning of 'stillborn' is 'the child born dead'. The Hanbali scholar Al-Buhooti said: “The stillborn, if it reached four months of age (in the womb), is washed and prayed over, even if it did not cry (i.e., right after birth, as is usual).”
The opinion holding the legality of praying over it is the opinion of Ahmad. Ibn Qudaamah said in Al-Mughni: “This is the opinion of Sa‘eed ibn Al-Musayyib, Ibn Seereen and Is-haaq, and Ibn ‘Umar prayed over his daughter's son who was born dead.”
Offering condolences for the child's death is legislated because it is an affliction that is included in the Hadeeth: “Whoever condoled an afflicted person, will receive a similar reward.” [At-Tirmithi, Ibn Maajah; there is some weakness in the chain.] It is said in Tuhfat Al-Ahwathi (by Al-Mubaarakfoori): “(Whoever condoled an afflicted person) means even if there was no death (i.e. it is general).”
Likewise, it is recommended to give the child a name, in accordance with the opinions of Ahmad and Ash-Shaafi‘i.
Allaah Knows best.