0

My Django project has the following structure:

enter image description here

I am displaying questions.html in the browser:

<html>
  <head>
  </head>

  <body>
  Questions:

  <div id="questionSpace"></div>

  <script src="../js/frontEnd/src/App.js"/>

  </body>
</html>

questions.html is referencing the code from App.js which is:

import {React, Component} from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import './App.css';

class App extends Component {

  componentWillMount() {
    fetch(`http://localhost:8000/api/questions`)
      .then(result => {
        this.setState({questions: result.json()})
      })
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <ul>
          {this.state.questions.map(question => <li>question.content</li>)}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("questionSpace"));

For some reason, the javascript code is not included in the html page.

Any idea what could cause this?

bsky
  • 19,326
  • 49
  • 155
  • 270
  • Have you [checked your console for errors?](http://stackoverflow.com/documentation/javascript/185/getting-started-with-javascript/714/using-console-log) Are you preprocessing that code at all? React uses JSX which isn't natively supported in browsers and `import` is not supported in most browsers yet. Your code needs to be compiled. – Mike Cluck Nov 08 '16 at 15:40

1 Answers1

2

First of all you may want to use <script ...></script> instead of <script ... />

Second of all, if you use JSX and/or ES6 (e.g. the import syntax), you want to compile those first, then include the compiled .js in the page, not the source JSX.

Finally, if questions.html is rendered as a Django template, including <script src="../js/frontEnd/src/App.js"></script> wouldn't work unless you setup Django to serve static files, e.g. on /static/

  <script src="/static/js/frontEnd/dist/App.js"></script>

Notice above I use dist/App.js instead of src/App.js to emphasize that you will eventually need a compiled .js

Community
  • 1
  • 1
bakkal
  • 54,350
  • 12
  • 131
  • 107