Is fanfiction illegal?

I’ve heard that it is technically to write an original story about characters from a tv show or a comic book, etc., and post it on the internet?

Is that true? and if so, does it have to do with trademark law or copyright law?