I am new to Typescript. I am getting the following error when using the HTMLElement type within a forEach loop:
ERROR in ./app/javascript/mount.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/me/projects/mathllc/app/javascript/mount.jsx: Unexpected token, expected "," (7:34)
5 | const mountPoints = document.querySelectorAll('[data-react-component]')
6 | mountPoints.forEach((mountPoint) => {
> 7 | const dataset = (mountPoint as HTMLElement).dataset
| ^
8 | const componentName = dataset['reactComponent']
9 | const Component = components[componentName]
10 | if (Component) {
I am following this tutorial by @Ryan Bigg : https://egghead.io/blog/rails-graphql-typescript-react-apollo
My code is here:
import ReactDOM from 'react-dom'
export default function mount(components = {}) {
document.addEventListener('DOMContentLoaded', () => {
const mountPoints = document.querySelectorAll('[data-react-component]')
mountPoints.forEach((mountPoint) => {
const dataset = (mountPoint as HTMLElement).dataset
const componentName = dataset['reactComponent']
const Component = components[componentName]
if (Component) {
const props = JSON.parse(dataset['props'])
ReactDOM.render(<Component {...props} />, mountPoint)
} else {
console.log(
'WARNING: No component found for: ',
dataset.reactComponent,
components,
)
}
})
})
}
Thanks for any help!
Looking at the error - ERROR in ./app/javascript/mount.jsx) - it appears that you are not using a .tsx file and the keyword as is not valid Javascript so you either should remove the as HTMLElement because Javascript does not care about types or change the filename to mount.tsx - if you are using a Typescript compiler in your build chain.