Because of the electrostatic force of attraction that exists between the cations and anions.
Ionic compounds are made up of cations, which are positively charged ions, and anions, which are negatively charged ions.
When a metal atom and a nonmetal atom react, a transfer of electrons takes place. The metal atom will give up its electrons and develop a positive charge, while the nonmetal atom will take these electrons and develop a negative charge.
When this happens, the strong electrostatic attraction that exists between positive and negative charges kicks into high gear and bonds these two ions together.
Now imagine you have a whole bunch of metal and nonmetal atoms that react and become cations and anions.
Each cation will be attracted to more than one anion, and each anion to more than one cation. As a result, a giant 3D lattice structure in which cations are surrounded by anions and anions are surrounded by cations is formed.