Jim Jimson
Jim Jimson

Reputation: 2528

"Cannot read property 'MDCSwitch' of undefined" error when importing an MDC Switch component

I'm writing a Node app using express and material-components-web and I'm having a problem where TextField works but Switch does not.

Here's the code I'm using to attach the relevant JS to the elements:

  [].slice.call(document.querySelectorAll('.mdc-text-field')).forEach(
  function(ele) {
    mdc.textField.MDCTextField.attachTo(ele);
  });

  [].slice.call(document.querySelectorAll('.mdc-switch')).forEach(
  function(ele) {
    mdc.switch.MDCSwitch.attachTo(ele);
  });

When I comment out the code for the textfield it stops working, so the mdc.textField.MDCTextField part is definitely working.

The error I get in Chrome Dev Tools is:

(index):446 Uncaught TypeError: Cannot read property 'MDCSwitch' of undefined
    at (index):446
    at Array.forEach (<anonymous>)
    at (index):444

My package.json file looks like this:

{
  "name": "emergencyregister",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {    
    "debug": "~2.6.9",
    "ejs": "^2.6.2",
    "eslint": "^5.7.0",
    "express": "^4.16.4",
    "helmet": "^3.20.0",
    "http-errors": "~1.6.2",
    "material-components-web": "^3.1.0",
    "mysql": "^2.16.0",
    "node-sass": "^4.12.0",
    "node-sass-middleware": "^0.11.0",
    "serve-favicon": "^2.5.0"
  },
  "devDependencies": {}
}

Any ideas?

Upvotes: 2

Views: 911

Answers (2)

Will Ernest
Will Ernest

Reputation: 84

A bit of history on why it's different than the rest.

switch is a reserved keyword in JS, so the component name had to be modified.

Upvotes: 4

Jim Jimson
Jim Jimson

Reputation: 2528

Turns out the code I should have been using was:

  [].slice.call(document.querySelectorAll('.mdc-switch')).forEach(
  function(ele) {
    mdc.switchControl.MDCSwitch.attachTo(ele);
  });

To work this out I printed the mdc object to the console to find all of the different items:

enter image description here

Upvotes: 8

Related Questions