While it may be hard to believe, terrorists are not mentally ill. Most terrorists are, in their own minds, driven to harm innocent people and create fear in order to further their political, religious or other ideological goals. They must have reviewed the costs and benefits of their actions in order to conclude it makes sense to carry out a terrorist activity, even if it means they will die.
Often times, they can be convinced and reinforced that they are thinking correctly when they follow alluring leaders who can make them feel a sense of belonging, encouragement, and loyalty to a group of people who share the same religion, values, or culture as they themselves feel.