简体   繁体   中英

My react app doesn't render as expected. Why is this happening?

So, I am learning React (from this video ) and I am stuck in the beginning.

I set up 2 files: App.js and index.html , just like in the video.

I installed the npm packages react and react-dom too.

This is the following code of the files;

index.html :

<!DOCTYPE html>
<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <div id="root"></div>
        <script src='/App.js'></script>
    </body>
</html>

App.js :

import React from 'react'
import ReactDOM  from 'react-dom'

export default ReactDOM.render(<h1>Test</h1>, document.getElementById("root"));

  • Both files are in the same directory.

But whenever I hit the index.html in the browser it returns me nothing, and I am just following the instructions from the video that I mentioned. Why is this happening?

Thanks!

You didn't include the react js file (the framework) in your html file.

From the video, you can see on the left pane the "dependencies" section. It has both react and react-dom as dependencies.

In your App.js you are trying to export the ReactDOM.render() statement.

Try changing it to this

import React from 'react'
import ReactDOM  from 'react-dom'

ReactDOM.render(<h1>Test</h1>, document.getElementById("root"));

If your index.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop

var __html = require('./index.html');
var index= { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={index} />
    );
  }
});

This technique goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM