Home > Software design >  React will not render to screen
React will not render to screen

Time:06-21

I am trying to test my react to make sure it can render but for some reason it will not work. I am using npx create-react-app to create my app. Please help

Javascript:

import React from "react"
import ReactDOM from "react-dom"

const app = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  )
}
        
ReactDOM.render(app(), document.getElementById("root"))

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="index.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <title>React App</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>

CodePudding user response:

Instead of ReactDOM.render(app()... should be ReactDOM.render(<App>, because you want to render a component not a function,

Also as you mentioned you are using create-react-app, the default imports are these:

import React from 'react';
import ReactDOM from 'react-dom/client';

Which means you need to update your ReactDOM import

Note: every component should start with capital letter, so change const app to const App


Here is a snippet with the changes:

import React from "react"
import ReactDOM from "react-dom/client"

const App = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  )
}
        
ReactDOM.render(<App/>, document.getElementById("root"))

CodePudding user response:

already answered but comments should help to understand

import React from "react"
    import ReactDOM from "react-dom"
    
// component name should start with uppercase
    const App = () => {
      return (
        <div>
          <h1>Hello World</h1>
        </div>
      )
    }
         // render function takes a Reactelement as first parameter  
    ReactDOM.render(<App/>, document.getElementById("root"))
  • Related