This problem was similar to this, but I couldn't make it work with the direction I want to show:
I tried showing the contrapositive (the inverse of the linked problem), which is showing "if $X$ is disconnected, then all the continuous functions $f$ are surjective" but I'm very stuck.
My attempt was: $X$ disconnected $\implies X = A \cup B$ where $A$ and $B$ are disjoint open sets in $X$. And since $f$ is continuous, we know $f^{-1}(\{ 0 \}), f^{-1}(\{ 1 \})$, and $f^{-1}(\{ 0,\, 1 \})$ are all open in $X$.
My gut tells me because $A$ and $B$ are open, disjoint and cover $X$, that I could conclude, without loss of generality, that $f(A) = \{ 0 \}$ and $f(B) = \{ 1 \}$, which shows surjectivity. But I can't figure out if this idea is correct and, if it is, how to formalize it.
You are on the right track. We will show, that if $X$ is not connected then there exists a continuous function from $X$ to $\{0,1\}$ which is not constant. If $X$ is not connected we can find a subset $A$ which is not the empty set nor $X$ which is open and closed. Note that $A^c$ also shares this property. Hence define our required function $f$ to be s.t $f=0$ on $A$ and $f=1$ on $A^c$. Check that $f$ is continuous.