ronnyrr ronnyrr - 3 months ago 21
React JSX Question

React "document not defined" when including script

I'm using ReactJS with Routing, ES6, Babel and ESLint.
On click I want to add a CSS class using the classnames library, but I can't even use the

document.querySelector
. My whole application crashes and prints the error:
ReferenceError: document is not defined


import React from 'react';
import { connect } from 'react-redux';

export default class Nav extends React.Component {
constructor(props) {
super(props);

const sideNavToggleButton = document.querySelector('.js-toggle-menu');
sideNavToggleButton.addEventListener('click', () => {
console.info('clicked');
});
}

render() {
return (
<header>
<button role="tab" className="header__menu js-toggle-menu">Toggle nav menu</button>
<h1 className="header__title">App Shell</h1>
</header>
);
}
}


After some research I found out it might be my ESLint settings missing some environments, but after adding browser the application is still breaking.

module.exports = {
'parser': 'babel-eslint',
'plugins': [
'react'
],
'rules': {
'indent': [2, 'tab'],
'max-len': 0,
'no-console': [2, { allow: ['info', 'error']}],
'no-param-reassign': 0,
'react/jsx-indent': [2, 'tab'],
'react/jsx-indent-props': [2, 'tab'],
'no-new': 0
},
'env': {
'browser': true,
'node': true
}
};


Any idea?

Answer

You have to move this part of your code to the method componentDidMount()

const sideNavToggleButton = document.querySelector('.js-toggle-menu');
sideNavToggleButton.addEventListener('click', () => {
    console.info('clicked');
});

Because componentDidMount() is the method that is called after the first rendering here. After rendering you can do any dom manipulation.

Comments