[Tex/LaTex] How to add a hyperlink to the table of contents

hyperreftable of contents

I am trying to add a hyperlink under the section line in the toc, but I get a compilation error when I try. The code below will not compile if the commented line is uncommented. Is there a solution to this?

\documentclass{article}
\usepackage{hyperref, color}

\def\animal{zebra}
\def\mylabel{zzz}

\begin{document}

\tableofcontents

\section{Zoo}
%\addtocontents{toc}{\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
\addtocontents{toc}{\textcolor{blue}{\animal}}

\hypertarget{\mylabel}{\noindent Here is a zebra.} \\
Go to \hyperlink{\mylabel}{\textcolor{blue}{\animal}}.

\end{document}

Best Answer

In your case you need to add \protect before \hyperlink:

\addtocontents{toc}{\protect\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
%                   ^^^^^^^^

With the following MWE

\documentclass{article}
\usepackage{color}
\usepackage{hyperref} % <================= should be last called package

\def\animal{zebra}
\def\mylabel{zzz}


\begin{document}

\tableofcontents

\section{Zoo}
\addtocontents{toc}{\protect\hyperlink{\mylabel}{\textcolor{blue}{\animal}}}
%\addtocontents{toc}{\textcolor{blue}{\animal}}

\hypertarget{\mylabel}{\noindent Here is a zebra.} \\
Go to \hyperlink{\mylabel}{\textcolor{blue}{\animal}}.

\end{document}

you get the wished result:

wished result