Stimulus Discourse

Optional targets


Is it possible to have optional targets? If I remove the HTML that includes the reference to the target, the whole Stimulus controller fails.

I can of course, not use a target on those particular element and get them using querySelector


You can use the has*Target properties to check for optional target elements:

export default class extends Controller {
  static targets = [ "name" ]

  connect() {
    if (this.hasNameTarget) {


Thanks @javan, I totally skipped over that part in the docs.