Badrush
Badrush

Reputation: 1287

React.JS simple component not rendering nested html tag

This is a simple piece of code. I am trying to get my first component to run and I followed the tutorial and this is their code for creating the component.

It works in that it does inject the first into the html document but the is missing.

For some reason it worked perfectly for the instructor in the video, as you can see here: https://youtu.be/G40iHC-h0c0?t=392

import React from "react";
import { render } from "react-dom";

class basicDiv extends React.Component {
    render(){
        return(
            <div>
                <h1>Hi my friend</h1>
            </div>
        );
    }
}

render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));

here is the index.html file:

<!doctype html>

<html>

<head>

</head>
<body>
    <div class="componentPlaceHolder" style="border:1px solid black;min-height:100px;">

    </div>

    <script src="/app/bundle.js"></script>
</body>

</html>

Upvotes: 0

Views: 1573

Answers (2)

Joshua Maddox
Joshua Maddox

Reputation: 141

D-reaper is correct. You should also return the render function to an ID in your html rather than to a .class

In your html change:

<div class=componentPlacholder>
to <div id="componentPlaceholder">`

Then at the bottom of your React component change:

render(<basicDiv/>, window.document.querySelector(".componentPlaceHolder"));
to render(<BasicDiv />, getElementById(componentPlacholder));

Don't forget to rename your component from basicDiv to BasicDiv as D-reaper mentioned

You can technically return to a .class but since it looks like you are learning it seemed helpful to alert you that you will cause yourself a lot of issues if you are not returning to an ID.

Upvotes: 1

Mμ.
Mμ.

Reputation: 8542

React component class has to be capitalised. Change that and your code will work. See this doc for more details on JSX.

class BasicDiv extends React.Component {
    render(){
        return(
            <div>
                <h1>Hi my friend</h1>
            </div>
        );
    }
}

ReactDOM.render(<BasicDiv/>, window.document.querySelector(".componentPlaceHolder"));
<!doctype html>

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

</head>
<body>
    <h2>This is a Skeleton React Build</h2>
    <p>It uses babel to convert ES6 code to ES5</p>
    <p>This is a good place to start building your app. This is a blank canvas.</p>

    <h2>Below is where my first component will be injected</h2>
    <p>If you see anything in the box below... it works!</p>
    <div class="componentPlaceHolder" style="border:1px solid black;min-height:100px;">

    </div>

    <script src="/app/bundle.js"></script>
</body>

</html>

Upvotes: 4

Related Questions