I'm getting this error in my react application in production:
TypeError: Cannot read properties of null (reading 'useRef')
With sourcemap enabled, it shows error in react.production.min.js
What's strange is, I'm getting this only on a particular route. All other routes are working fine (Even though I'm using useRef
s in multiple files.).
Since the local build is working fine, I'm unable to reproduce the issue locally.
I tried the following things:
- Reverting to previous working commit.
- Reinstalling
node_modules
on prod machine - Switching from Yarn to NPM
I'm using express to host the static build files. Here's the code:
const helmet = require('helmet');
const path = require('path');
const app = express();
const fs = require('fs');
app.disable('x-powered-by');
app.use(helmet.frameguard({ action: 'DENY' }));
app.use(express.static(__dirname));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'), {
maxAge: 86400000,
});
});
app.listen(process.env.PORT || 8080, function () {
console.log(`Frontend start on http://localhost:8080`);
});
Edit: React Component:
import React, { useRef } from 'react';
const ConfigForm = (props) => {
const scrollTopRef = useRef(null);
const scrollToTop = () => {
if (scrollTopRef && scrollTopRef.current) {
scrollTopRef.current.scrollTo({
top: 0,
behavior: 'smooth',
});
}
};
const onButtonClick = () => {
scrollToTop();
}
return (
<div className="client-configs" ref={scrollTopRef}>
<button onClick={onButtonClick}>Scroll To Top</button>
</div>
);
}
export default ConfigForm;