0

I want to set the routes for my web app using Express, and I'm also using React to handle the front end. The problem is that I don't understand how to route things properly when using React components.

I have in my index.html:

<script> document.getElementById("input").onchange = function() {  ...  } </script>

And my App.js:

class App extends Component {
    render() {
        return ( <div><input id="input" /></div> );
    }

}

And router.js:

app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})

And static/index.js:

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

The problem is that I'm getting "Cannot set property 'onchange' of null". Obviously the App object was not rendered, but I don't understand why. How can I make this work?

j08691
  • 204,283
  • 31
  • 260
  • 272
Alexmedkex
  • 427
  • 5
  • 13

2 Answers2

0

I believe you need the express router

Differences between express.Router and app.get?

var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/', function(req, res) {
    res.sendFile(path.join(__dirname), '../public/index.html');
});
andrewgi
  • 620
  • 1
  • 7
  • 22
0

Try two things:

  1. Remove the document.getElementById("input").onchange inside of the script tag and instead put console.log('I am running the script tag')
  2. Put a console.log('I am rendering the App via react' inside of yourrendermethod, right abovereturn`.

I am imagining that the script tag gets "evaluated" before react has done anything with the DOM, causing document.getElementById to not return anything, hence your null.

If this is true, you will see your I am running the script tag before your see I am rendering the App.

Tim Roberts
  • 1,120
  • 2
  • 9
  • 25