skip to Main Content

I recently learned React and I tried to practice what I learned, I made a container App that would render a div with a form and its children to an HTML file

import ReactDOM from "react-dom";
import App from "./App";
class App extends React.Component () {
    constructor (props) {
        super(props)
    }
    mainDiv () {
            return (
                <form id="quote-box">
                    <p id="text"></p>     
                    <div>
                        <span id="author"></span>
                        <button id="quoteButton">New Quote</button>
                    </div>
                </form>
            )
    }

    render() { return (<mainDiv/>)}
}
ReactDOM.render(<App />,  document.getElementById("root")); 

it wasn’t rendering so I tried changing its extension from jsx to Js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>random-quote-machine</title>
</head>
<body>
    <script type="text/babel" src="react.js"></script>
</body>
</html>

But it still did not work, what could I be doing wrong?

2

Answers


  1. You need to have an element with id='root' under your body tag in your html file to render your React App.

    <div id="root"></div>
    

    Refer Documentation

    Login or Signup to reply.
  2. You just need to add a html div with the id=’root’ to your index.html file like the mentioned in the documentation https://legacy.reactjs.org/docs/rendering-elements.html
    So your code will look like

    <!DOCTYPE html>
      <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>random-quote-machine</title>
    </head>
    <body>
      <script type="text/babel" src="react.js"></script>
      <div id="root"></div>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search